java文件操作(普通文件以及配置文件的读写操作)
读取普通文件 :
/** * xiangqiao123欢迎你 如果对代码有疑问可以加qq群咨询:151648295 * * 读取MyFile文件 */ package com.xiangqiao123.file; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; public class ReadFile { public static void main(String[] args) { try { // 注意路径的写法,java默认的路径是到根目录下 File f = new File("src/MyFile.text"); if (f.isFile() && f.exists()) { // 进行编码转换,避免出现乱码 InputStreamReader read = new InputStreamReader(new FileInputStream(f), "utf-8"); BufferedReader br = new BufferedReader(read); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } read.close(); }else { System.out.println("文件读取失败"); } } catch (Exception e) { e.printStackTrace(); } } }
写普通文件:
/** * xiangqiao123欢迎你 如果对代码有疑问可以加qq群咨询:151648295 * *向文件里面写内容 */ package com.xiangqiao123.file; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; public class WriteFile { public static void main(String[] args) { // 注意文件的路径写法 File f = new File("src/MyFile.text"); if (f.isFile() && f.exists()) { System.out.println("123"); try { // new FileOutputStream(f, true) // 第二个参数是true表示以后写的内容不会覆盖原来的,而是添加内容 OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(f, true), "utf-8"); BufferedWriter bw = new BufferedWriter(writer); // BufferedWriter bw=new BufferedWriter(new FileWriter(f,true)); bw.write("写入文件的内容"); // 换行操作 bw.newLine(); // 清除缓冲,如果不写:信息不会写入文件 bw.flush(); writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
读配置文件:
/** *xiangqiao123欢迎你 如果对代码有疑问可以加qq群咨询:151648295 * 读取配置文件info.properties */ package com.xiangqiao123.file; import java.io.File; import java.io.FileInputStream; import java.util.Properties; public class ReadInfoFile { public static void main(String[] args) { Properties p = new Properties(); //注意路径 File f = new File("src/info.properties"); try { FileInputStream fis = new FileInputStream(f); p.load(fis); System.out.println(p.get("first")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
写配置文件:
/** * xiangqiao123欢迎你 如果对代码有疑问可以加qq群咨询:151648295 * * 网配置文件里面写内容 */ package com.xiangqiao123.file; import java.io.File; import java.io.FileOutputStream; import java.util.Properties; public class WriteInfoFile { public static void main(String[] args) { Properties p = new Properties(); File f = new File("src/info.properties"); try { FileOutputStream fos = new FileOutputStream(f, true); // 要添加的内容 p.setProperty("first", "hello"); p.store(fos, null); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }