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     }

文件流基礎,以方便查閱!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM