我运行此代码,我得到“文件写入!”当我打开文件看它时,所写的每件事都没有任何意义。你可以理解我想在文件中写012345678910。是否有任何其他方式可以在文件中写入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呢?
答案 0 :(得分:4)
写一个字符。
<强>参数:强>
c - 指定要写入的字符
writer.write(String.valueOf(integer));
答案 1 :(得分:1)
BufferedWriter#write(int i)
在Unicode Table中写出与i
对应的字符,您可以使用
System.out.print((char)k);
现在,如果你想写k
的int值,你应该使用PrintWriter
PrintWriter printW = new PrintWriter(fileW);
printW.print(k);
您还可以查看PrintStream#print()
方法(System.out
是PrintStream的实例),但编写器优先于Streams进行字符I / O操作。