写Properties
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class WriteProperties { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File file = new File("D://Properties.txt"); Properties property = new Properties(); try { OutputStream os = new FileOutputStream(file); property.setProperty("NAME", "Ben Zeph"); property.setProperty("AGE", "23"); property.setProperty("MAJOR", "Computer Science"); try { property.store(os, "This is properties file"); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("数据写入完成"); } }
读Properties
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ReadProperties { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String name = ""; String age = ""; String major = ""; Properties property = new Properties(); File file = new File("D://Properties.txt"); try { InputStream is =new FileInputStream(file); try { property.load(is); name = property.getProperty("NAME"); age = property.getProperty("AGE"); major = property.getProperty("MAJOR"); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("NAME:"+name); System.out.println("AGE:"+age); System.out.println("MAJOR:"+major); } }