VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • C#
  • Python
  • PHP
  • Excel
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Eclipse
    • Phần mềm tiện ích
    • Cấu trúc DL&GT
    • Selenium Test
Java Cơ Bản Các Khái Niệm Java OOPs Java String Java I/O

Ví dụ Java I/O

Java Input/Output Các ví dụ về Java I/O

Thao Tác Với File Trong Java

Tạo file trong java Đọc file với BufferedInputStream trong java Đọc file với BufferedReader trong java Đọc ghi file trong java Append nội dung vào file trong java Delete file trong java Delete nhiều file dựa vào phần mở rộng trong java Tìm các file dựa vào phần mở rộng trong java Đổi tên file trong java Copy file trong java Move file trong java Check file tồn tại trong java Check file ẩn trong java Liệt kê tất cả file và folder trong một folder Get thư mục hiện tại trong Java Read properties file trong java

Thao Tác Với Folder Trong Java

Check thư mục rỗng trong java Tạo thư mục trong java Xóa thư mục trong java Copy thư mục trong java

ZIP File Trong Java

ZIP file trong java
Xử Lý Ngoại Lệ Các Lớp Lồng Nhau Đa Luồng (Multithreading) Java AWT Java Swing Lập Trình Mạng Với Java Java Date Chuyển Đối Kiểu Dữ Liệu Java Collections Java JDBC Các Tính Năng Mới Trong Java Bài Tập Java Có Lời Giải Câu Hỏi Phỏng Vấn Java
1 / 3
❮ ❯

Read properties file trong java


Get thư mục hiện tại trong Java
Check thư mục rỗng trong java

Properties file (.properties) chủ yếu được sử dụng trong các công nghệ liên quan đến Java để lưu trữ các tham số có thể cấu hình của một ứng dụng. Properties là các giá trị được quản lý theo các cặp key/value. Trong mỗi cặp, key và value đều có kiểu String. Key được sử dụng để truy xuất value, giống như tên biến được sử dụng để truy xuất giá trị của biến.

Bài này hướng dẫn bạn cách read properties file trong java:

  1. Read properties file từ thư mục hiện tại.
  2. Read properties file từ resources (classpath).
  3. Read properties file bằng cách sử dụng Singleton pattern.

Nội dung chính

  • Định nghĩa file properties
  • 1. Read properties file từ thư mục hiện tại
  • 2. Read properties file từ resources (classpath)
  • 3. Read properties file sử dụng Singleton pattern

Định nghĩa file properties

File properties có nội dung như sau, được sử dụng trong các ví dụ của bài này:

username=admin
password=123456

1. Read properties file từ thư mục hiện tại

Ví dụ 1: Read properties file trong java

Tạo file config.properties trong cùng thư mục với java resources.

File: ReadPropertiesExample1.java

package com.realtut;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadPropertiesExample1 {
    private static final String FILE_CONFIG = "\\config.properties";

    public static void main(String[] args) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            String currentDir = System.getProperty("user.dir");
            inputStream = new FileInputStream(currentDir + FILE_CONFIG);

            // load properties from file
            properties.load(inputStream);

            // get property by name
            System.out.println(properties.getProperty("username"));
            System.out.println(properties.getProperty("password"));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close objects
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Kết quả:

admin
123456

2. Read properties file từ resources (classpath)

Ví dụ 2: Read properties file trong java

Tạo file config.properties trong java resources.

File: ReadPropertiesExample2.java

package com.realtut;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadPropertiesExample2 {
    private static final String FILE_CONFIG = "\\config.properties";

    public static void main(String[] args) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = ReadPropertiesExample2.class.getClassLoader()
                    .getResourceAsStream(FILE_CONFIG);

            // load properties from file
            properties.load(inputStream);

            // get property by name
            System.out.println(properties.getProperty("username"));
            System.out.println(properties.getProperty("password"));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close objects
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Kết quả:

admin
123456

3. Read properties file sử dụng Singleton pattern

File: ReadPropertiesSingleton.java

package com.realtut;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ReadPropertiesSingleton {
    private static final String FILE_CONFIG = "\\config.properties";
    private static ReadPropertiesSingleton instance = null;
    private Properties properties = new Properties();

    /**
     * Use singleton pattern to create ReadConfig object one time and use
     * anywhere
     *
     * @return instance of ReadConfig object
     */
    public static ReadPropertiesSingleton getInstance() {
        if (instance == null) {
            instance = new ReadPropertiesSingleton();
            instance.readConfig();
        }
        return instance;
    }

    /**
     * get property with key
     *
     * @param key
     * @return value of key
     */
    public String getProperty(String key) {
        return properties.getProperty(key);
    }

    /**
     * read file .properties
     */
    private void readConfig() {
        InputStream inputStream = null;
        try {
            String currentDir = System.getProperty("user.dir");
            inputStream = new FileInputStream(currentDir + FILE_CONFIG);
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close objects
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

File: Test.java

package com.realtut;

public class Test {
    public static void main(String[] args) {
        ReadPropertiesSingleton demo = ReadPropertiesSingleton.getInstance();
        System.out.println(demo.getProperty("username"));
        System.out.println(demo.getProperty("password"));
    }
}

Kết quả:

admin
123456

Get thư mục hiện tại trong Java
Check thư mục rỗng trong java

Recent Updates

Xuất dữ liệu ra màn hình console trong JavaCài đặt môi trường JavaJava Swing - Bài tập quản lý sinh viên trong javaLinkedList trong javaArrayList trong javaBài tập java có lời giảiXác thực dữ liệu (Data Validation) trong ExcelGiới thiệu các hàm có sẵn trong ExcelSheet Options trong ExcelHướng dẫn lập trình Python với PyCharm Community EditionHướng dẫn lập trình Python với Visual Studio CodeGiới thiệu CSS3Sắp Tết 2026 Rồi! - Còn bao nhiêu ngày nữa là đến tết 2026?

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn
Danh Sách Bài Học

Học Java | Hibernate | Spring
Học Excel | Excel VBA
Học Servlet | JSP | Struts2
Học C | C++ | C#
Học Python
Học SQL

Bài Tập Có Lời Giải

Bài tập Java
Bài tập C
Bài tập C++
Bài tập C#
Bài tập Python
Ví dụ Excel VBA

Câu Hỏi Phỏng Vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml