Java PrintWriter只写部分文本
由于某些原因,我的字符串部分由PrintWriter编写。因此,我的文件中有部分文本。方法如下:Java PrintWriter只写部分文本,java,printwriter,Java,Printwriter,由于某些原因,我的字符串部分由PrintWriter编写。因此,我的文件中有部分文本。方法如下: public void new_file_with_text(String text, String fname) { File f = null; try { f = new File(fname); f.createNewFile(); System.out.println(text)
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
} catch (IOException e) {
e.printStackTrace();
}
}
当我将文本打印到控制台时,我可以看到数据都在那里,没有任何内容丢失,但显然当PrintWriter执行其工作时,部分文本丢失了。。。我不懂..尝试使用out.flush()代码>紧跟在行后输出。打印(文本)代码>
以下是写入文件的正确方法:
public void new_file_with_text(String text, String fname) {
try (FileWriter f = new FileWriter(fname)) {
f.write(text);
f.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
在丢弃打开的流之前,您应该始终关闭流。这将释放JVM在文件系统上打开文件时必须使用的一些相当昂贵的系统资源。如果不想关闭流,可以使用Writer\flush
。这将使您的更改在文件系统上可见,而无需关闭流。关闭流时,隐式刷新所有数据
流总是缓冲数据,以便只有在有足够的数据要写入时才写入文件系统。当流以某种方式认为数据值得写入时,它会不时地自动刷新数据。写入文件系统是一项昂贵的操作(需要花费时间和系统资源),因此只有在确实必要时才应执行。因此,如果希望立即写入,则需要手动刷新流的缓存
通常,请确保始终关闭流,因为它们使用了相当多的系统资源。Java有一些在垃圾收集时关闭流的机制,但这些机制只能被视为最后的手段,因为流在实际被垃圾收集之前可以存在相当长的时间。因此,始终使用try{}finally{}
确保流关闭,即使在流打开后出现异常。如果您不注意这一点,您将得到一个IOException
信号,表明您打开了太多的文件
您希望按如下方式更改代码:
public void new_file_with_text(String text, String fname) {
File f = null;
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
try {
out.print(text);
} finally {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
您应该关闭您的文件:
PrintWriter out = new PrintWriter(f, "UTF-8");
try
{
out.print(text);
}
finally
{
try
{
out.close();
}
catch(Throwable t)
{
t.printStackTrace();
}
}
您必须始终在finally块中或使用Java 7 try with resources工具关闭流(这也将刷新流):
PrintWriter out = null;
try {
...
}
finally {
if (out != null) {
out.close();
}
}
或
如果不关闭流,不仅不会将所有内容都刷新到文件中,而且在某个时候,您的操作系统将无法使用可用的文件描述符。我测试了您的代码。您忘记关闭PrintWriter对象,即out.close
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
out.close(); // <--------------
} catch (IOException e) {
System.out.println(e);
}
试试看{
f=新文件(fname);
f、 createNewFile();
System.out.println(文本);
PrintWriter out=新的PrintWriter(f,“UTF-8”);
打印(文本);
out.close();/…或在finally
块中,以及out.close()
!只需添加我们可以缩短片段PrintWriter out=new PrintWriter(f,“UTF-8”);尝试{out.print(text);}finally{out.close();}
,使用它将自动为我们处理关闭资源:try>(PrintWriter out=新的PrintWriter(f,“UTF-8”){out.print(text);}
。
try {
f = new File(fname);
f.createNewFile();
System.out.println(text);
PrintWriter out = new PrintWriter(f, "UTF-8");
out.print(text);
out.close(); // <--------------
} catch (IOException e) {
System.out.println(e);
}