VietTuts

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

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • Python
  • PHP
  • Eclipse
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Phần mềm tiện ích
    • Cấu trúc dữ liệu và giải thuật
    • Học lập trình C#
    • 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

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

Toán tử dấu 2 chấm (::) trong Java 8Lambda Expression - Biểu thức Lambda trong java 8Hướng dẫn lập trình Angular 7 với trình soạn thảo Visual Studio CodeGeolocation trong HTML5Audio và Video trong HTML5XML Validation - Xác nhận tài liệu XMLXML CDATA - CDATA trong XMLXML Declaration - Khai báo XMLCollection trong C#Reflection trong C#Bài tập Java - Sắp xếp nhanh (Quick Sort) trong JavaBài tập Java - Sắp xếp chèn (Insertion Sort) trong Java

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
Học servlet
Học jsp
Học Hibernate
Học Struts2
Học Spring
Học SQL

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

About VietTuts.Vn

Hệ thống bài học trên VietTuts.Vn bao gồm các bài lý thuyết và thực hành về các công nghệ java và công nghệ web. Các bài lý thuyết trên hệ thống VietTuts.Vn được tham khảo và tổng hợp từ các trang http://javatpoint.com, http://www.tutorialspoint.com, http://docs.oracle.com/en …

Scroll back to top

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