java读取写入文件
先来看一下java写入文件
1 public static void readTxt(String value) throws IOException { 2 FileWriter fw = null; 3 try { 4 // 如果文件存在,则追加内容;如果文件不存在,则创建文件 5 File f = new File("E:\\dd.txt"); 6 fw = new FileWriter(f, true); 7 } catch (IOException e) { 8 e.printStackTrace(); 9 } 10 PrintWriter pw = new PrintWriter(fw); 11 pw.println(new String(value.getBytes(), "utf-8")); 12 pw.flush(); 13 try { 14 fw.flush(); 15 pw.close(); 16 fw.close(); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 21 }
下面是java来读取文件
1 public static String readText() throws IOException { 2 String pathname = "E:\\dd.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径 3 String fileContent = ""; 4 File f = new File(pathname); 5 if (f.isFile() && f.exists()) { 6 InputStreamReader read = new InputStreamReader(new FileInputStream(f), "UTF-8"); 7 BufferedReader reader = new BufferedReader(read); 8 String line; 9 while ((line = reader.readLine()) != null) { 10 fileContent += line; 11 } 12 read.close(); 13 } 14 return fileContent; 15 }
文件流基础,以方便查阅!!!
llh