Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để đọc dữ liệu từ tệp thuộc tính trong Java?

Thuộc tính là một lớp con của lớp Hashtable và nó đại diện cho một tập hợp các thuộc tính liên tục. Thuộc tính có thể được lưu vào một luồng hoặc tải từ một luồng. Mỗi khóa và giá trị tương ứng của nó trong danh sách thuộc tính là một chuỗi.

Thuộc tính tệp có thể được sử dụng trong Java để ngoại hóa cấu hình và lưu trữ cặp khóa-giá trị . Phương thức Properties.load () của lớp Thuộc tính rất thuận tiện để tải. thuộc tính tệp ở dạng khóa-giá trị cặp .

Cú pháp

public class Properties extends Hashtable

tệp tin credentials.properties


Làm cách nào để đọc dữ liệu từ tệp thuộc tính trong Java?

Ví dụ

import java.io.*;
import java.util.*;
public class ReadPropertiesFileTest {
   public static void main(String args[]) throws IOException {
      Properties prop = readPropertiesFile("credentials.properties");
      System.out.println("username: "+ prop.getProperty("username"));
      System.out.println("password: "+ prop.getProperty("password"));
   }
   public static Properties readPropertiesFile(String fileName) throws IOException {
      FileInputStream fis = null;
      Properties prop = null;
      try {
         fis = new FileInputStream(fileName);
         prop = new Properties();
         prop.load(fis);
      } catch(FileNotFoundException fnfe) {
         fnfe.printStackTrace();
      } catch(IOException ioe) {
         ioe.printStackTrace();
      } finally {
         fis.close();
      }
      return prop;
   }
}

Đầu ra

username: admin
password: admin@123