[英]How do I save results into .txt file
I am using MAC OS and I would like to save my results into a .txt file but for some reasons its not outputting a .txt file. 我正在使用MAC OS,我想将结果保存到.txt文件中,但由于某些原因,它不会输出.txt文件。 This is the code:
这是代码:
public static void main(String[] args) throws FileNotFoundException {
int one = 1514;
int zero = 396;
for (int i = 0; i <= one; i++) {
System.out.println("1");
}
for (int x = 0; x <= zero; x++) {
System.out.println("0");
}
}
What the code does it simply outputs 1514 1's (as specified in int one variable) and underneath 1's it outputs 0's (as specified in int zeros variable). 代码的作用是简单地输出1514 1(在int一个变量中指定),在1之下则输出0(在int零变量中指定)。 I want whatever is printed (both 1's & 0's) to be saved in .txt file.
我希望将打印的所有内容(包括1和0)都保存在.txt文件中。 I found this code online but how do I combine into my code so that it prints first 1's and 0's?
我在网上找到了此代码,但是如何将其组合到我的代码中,以便打印出前1和0?
PrintWriter out = new PrintWriter("output.txt");
out.println();
out.close();
You need to print to the PrintWriter, as I've shown below 您需要打印到PrintWriter,如下所示
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter("output.txt");
out.println();
int one = 1514;
int zero = 396;
for (int i = 0; i <= one; i++) {
out.println("1");
}
for (int x = 0; x <= zero; x++) {
out.println("0");
}
out.close();
}
Like this: 像这样:
public static void main(String[] args) throws FileNotFoundException {
int one = 1514;
int zero = 396;
PrintWriter out = new PrintWriter("output.txt"); //create PrintWriter
for (int i = 0; i <= one; i++) {
out.println("1"); //Write "1"
}
for (int x = 0; x <= zero; x++) {
out.println("0"); //Write "0"
}
out.close(); //close PrintWriter
}
This will write to the text file instead of printing it out. 这将写入文本文件,而不是打印出来。 You will get the same thing in the text file as your code was printing.
您将在文本文件中得到与打印代码相同的结果。 I hope I understood your question right BTW.
希望我正确理解您的问题。
代替System.out.println("1")
,在for
循环上方声明您的PrintWriter,然后说out.println("1")
或零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.