2014-07-17 40 views

回答

-1

看起來,這只是語法糖,你有興趣在這裏你去:

// write 
new PrintWriter("the-file-name.txt", "UTF-8").append("this string").close(); 

// read 
String thisStr = new BufferedReader(new FileReader("the-file-name.txt")).readLine(); 
System.out.println(thisStr); 
+0

這是如何「不使用複雜的代碼'BufferedReader' ...」'? – Pshemo

+1

至少它可能泄露開放流,糟糕的風格。 – Durandal

+1

異常處理??'IOException' ?? – TheLostMind

0

您可以使用以下行來只讀取一個字符串中的所有文件內容。

String content = new Scanner(new File(filepath)).useDelimiter("\\Z").next(); 

使用java.util.Scanner

寫操作使用

PrintWriter printWriter=new PrintWriter("filename").append("content"); 
2

如何利用java.nio.file

String s = new String(Files.readAllBytes(Paths.get("input.txt"))); 

類如果你想要寫你從readAllBytes得字節文件您可以使用

Files.write(Paths.get("output.txt"), s.getBytes(), StandardOpenOption.CREATE); 

或不s字符串

Files.write(Paths.get("output.txt"), 
     Files.readAllBytes(Paths.get("input.txt")), 
     StandardOpenOption.CREATE); 

但在這種情況下Files.copy(source, target, options)似乎更好的選擇:

Files.copy(Paths.get("input.txt"), Paths.get("output.txt"), 
     StandardCopyOption.REPLACE_EXISTING); 
+0

感謝給的答案,它是在JDK 1.7可用,但不幸的是我的工作在JDK 1.6這樣的文件類不存在。 –

+0

那麼這是非常重要的信息,所以應該在你的問題中提到:/(誰會猜測它在Java 8的時代)。 – Pshemo

0

有一個大家族在java.nio.file.Files包方便的方法,如

但你也應該考慮使用lines(),它返回一個Stream<String>,這將讓你懶洋洋地讀取行並對其進行處理,當您去,而無需加載就堆整個文件。

相關問題