[英]Java File .write() a stream of integers
運行此代碼,我得到“文件已寫入!” 當我打開文件進行查看時,所寫的所有內容都沒有任何意義。 您可以理解,我要在文件中寫入012345678910。 除了buffW.write(k);
還有什么其他方法可以寫入文件buffW.write(k);
。 我還有其他錯誤嗎?
package thema4_create_write_read_file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FW {
public static void main(String[] args) {
File newFile = new File("newFile.txt");
if (newFile.exists()) {
System.out.println("The file already exists");
} else {
try {
newFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileWriter fileW = new FileWriter(newFile);
BufferedWriter buffW = new BufferedWriter(fileW);
for (int k = 0; k <= 10; k++) {
buffW.write(k); // This is where the problem occurs
}
buffW.close();
System.out.print("File written !");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
有什么辦法可以將(k)寫成整數而不是寫成字符串,然后再讀成int呢?
寫一個字符。
參數:
c-指定要寫入的字符的int
writer.write(String.valueOf(integer));
BufferedWriter#write(int i)
在Unicode表中寫入與i
對應的字符,您可以看一下將使用寫入什么
System.out.print((char)k);
現在,如果要寫入int的k
值,則可能應該使用PrintWriter
PrintWriter printW = new PrintWriter(fileW);
printW.print(k);
您也可以看一下PrintStream#print()
方法( System.out
是PrintStream的實例),但是對於字符I / O操作,寫程序比Streams更受首選。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.