Java 如何使用printwriter创建和写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25298582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use printwriter to create and write to a file
提问by Brandon Nolan
I am trying to create a new file and print data to said file using the printwriter class.
我正在尝试使用 printwriter 类创建一个新文件并将数据打印到所述文件。
My code looks like this
我的代码看起来像这样
File Fileright = new File("C:\GamesnewOrder.txt");
PrintWriter pw = new PrintWriter(Fileright);
for(int i =0;i<=Games2.length-1;i++)
{
pw.println(Games2[i]);
}
pw.close();
I do have the main method with a throwsIOException
.
我确实有一个带有throwsIOException
.
The error java.iofilenotfound
exception keeps appearing at the line where I am creating the printwriter. So is the printwriter not creating the file?
错误java.iofilenotfound
异常一直出现在我创建印刷机的那一行。那么印刷商没有创建文件吗?
回答by novice
the code works for me.
代码对我有用。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class NewClass {
void n() throws FileNotFoundException {
File Fileright = new File("/home/ubuntu/Documents/f.txt");
PrintWriter pw = new PrintWriter(Fileright);
for (int i = 0; i <= 3; i++) {
pw.println(i);
System.out.println(i);
}
pw.close();
}
public static void main(String[] args) throws FileNotFoundException {
new NewClass().n();
}
}
output:(in file: /home/ubuntu/Documents/f.txt)
输出:(在文件中:/home/ubuntu/Documents/f.txt)
0
1
2
3
0
1
2
3
回答by Jaskey
FileNotFoundException - If the given file object does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
FileNotFoundException - 如果给定的文件对象不表示现有的、可写的常规文件,并且无法创建该名称的新常规文件,或者在打开或创建文件时发生其他错误
Please check the file Permission, you may use canRead()
, canWrite()
to check that, but it may not be sufficient enough.
请检查文件 Permission,您可以使用canRead()
,canWrite()
来检查,但这可能还不够。