java 将偶数和奇数写入 dat 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11914450/
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
Writing even and odd numbers to a dat file
提问by Serenity
I have started learning Java and am having problem with a simple program that should write some content to numbers.dat
file.
我已经开始学习 Java 并且遇到了一个应该将一些内容写入numbers.dat
文件的简单程序的问题。
I am facing two problems:
我面临两个问题:
The output that I am getting is as follows:
2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462, 506, 552, 600, 650, 702, 756, 812, 870, 930, 992, 1056, 1122, 1190, 1260, 1332, 1406, 1482, 1560, 1640, 1722, 1806, 1892, 1980, 2070, 2162, 2256, 2352, 2450, 2550...
When it should be:
For even numbers:
2,4,6,8,10,12,14,……,98,100
For odd numbers:
2,4,6,8,10,12,14,……,98,100,1,3,5,7,9,……..97,99
My second problem is that the output is not getting written to
numbers.dat
file! It's all blank.Please someone help me with this. I would be really grateful
我得到的输出如下:
2, 6, 12, 20, 30, 42, 56, 72, 90, 110, 132, 156, 182, 210, 240, 272, 306, 342, 380, 420, 462, 50, 50 20 702, 756, 812, 870, 930, 992, 1056, 1122, 1190, 1260, 1332, 1406, 1482, 1560, 1640, 1722, 1806, 5, 5, 2, 5, 20, 5, 2, 5 ..
什么时候应该是:
对于偶数:
2,4,6,8,10,12,14,……,98,100
对于奇数:
2,4,6,8,10,12,14,……,98,100,1,3,5,7,9,……..97,99
我的第二个问题是输出没有写入
numbers.dat
文件!都是空白。请有人帮我解决这个问题。我会很感激
The question from the book that I am trying to solve is:
我试图解决的书中的问题是:
Write a program called TextFileIO.java to create a file named numbers.dat. Then create an algorithm that writes all even numbered integers from 1 to 100, separated by a comma.
After the file has been created, close and reopen the file and display the results to the screen. After the results have been displayed append the odd number integers from 1 to 100, separated by a comma to the end of the file. Reopen the file and display the results. The contents of the file should be the even numbers from 1 to 100 separated by a comma followed by the odd number from 1 to 100 separated by a comma. The output of this program would be something like the following:
2,4,6,8,10,12,14,……,98,100
2,4,6,8,10,12,14,……,98,100,1,3,5,7,9,……..97,99
编写一个名为 TextFileIO.java 的程序来创建一个名为 numbers.dat 的文件。然后创建一个算法,写入从 1 到 100 的所有偶数整数,以逗号分隔。
创建文件后,关闭并重新打开文件并将结果显示在屏幕上。显示结果后,将 1 到 100 之间的奇数整数(用逗号分隔)附加到文件末尾。重新打开文件并显示结果。文件的内容应该是 1 到 100 之间用逗号分隔的偶数,然后是 1 到 100 之间用逗号分隔的奇数。该程序的输出类似于以下内容:
2,4,6,8,10,12,14,……,98,100
2,4,6,8,10,12,14,……,98,100,1,3,5,7,9,……..97,99
Below is the code that I have tried so far:
以下是我迄今为止尝试过的代码:
textFileIO.java
文本文件IO
package package1;
import java.io.*;
import java.util.*;
//class definition
public class textFileIO{
//The main function
public static void main(String args[]) {
//This declares a file to open.
File outFile = new File("numbers.dat");
int sumEven = 0;
int sumOdd = 0;
//File IO requires a try/catch block to prevent the program from crashing
try {
//a buffered writer is used to allow us to write to the file.
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
//This for loop handles adding all of the numbers together
for(int i = 1; i < 100; i += 2) {
sumEven += i + 1;
writer.write("" + sumEven + ", ");
}
//adding a new line and closing the file
writer.newLine();
writer.close();
//A buffered Reader is used for reading a new file.
BufferedReader reader = new BufferedReader(new FileReader(outFile));
//Because I only add a new line at the end, I only need to read the first line.
System.out.println(reader.readLine());
//I need to write again, so I close the reader and open the writer.
reader.close();
//you need to create another object to append to the file
//writer.open();
BufferedWriter writer2 = new BufferedWriter(new FileWriter(outFile));
//This for loop is identical to the previous one, except for odd numbers
for(int i = 1; i < 100; i += 2) {
sumOdd += i;
writer2.write("" + sumOdd + ", ");
}
writer.newLine();
writer.close();
//The same here. You need to create another reader
//reader.open();
BufferedReader reader2 = new BufferedReader(new FileReader(outFile));
System.out.println(reader2.readLine());
}
catch (Exception e) {
}
}
}
Edit 2
编辑 2
I changed my code and this is my latest code. i am still having problems. The console output screen is showing 49 and 50 as out put annnd my numbers.dat file is now showing only comma separated list f odd numbers...what am I doing wrong now?? :( Please help me!
我更改了代码,这是我的最新代码。我仍然有问题。控制台输出屏幕显示 49 和 50 作为输出,并且我的 numbers.dat 文件现在只显示逗号分隔的奇数列表......我现在做错了什么?:( 请帮我!
import java.io.*;
import java.util.*;
public class TextFileIO {
public static void main(String[] args) throws Exception {
//Clear the contents of numbers.dat if already exists and populated
File fileOne = new File("numbers.dat");
fileOne.delete();
File newFile = new File("numbers.dat");
newFile.createNewFile();
//Create writer object
PrintWriter writer = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is even, write to file
if (i % 2 == 0) {
writer.print(i + ",");
}
}
//Close writer object.
writer.close();
//Read from file
FileInputStream fileStream = new FileInputStream("numbers.dat");
DataInputStream in = new DataInputStream(fileStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//Print line
System.out.println(reader.read());
reader.close();
//Write all odd numbers to file
PrintWriter writer2 = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is odd, write to file
if (i % 2 == 1) {
writer2.print(i + ",");
}
}
writer2.close();
//Read from file
FileInputStream fileStream2 = new FileInputStream("numbers.dat");
DataInputStream in2 = new DataInputStream(fileStream2);
BufferedReader reader2 = new BufferedReader(new InputStreamReader(in2));
//Print line
System.out.println(reader2.read());
reader.close();
}
}
Edit 3:Guys I am still unable to get the desired output. I am still getting the output in console as 49 and 50, and in numbers.dat file, the otput is still ONLy odd numbers separated by commas. I am unable to understand what exactly to change in my code :(
编辑 3:伙计们,我仍然无法获得所需的输出。我仍然在控制台中得到 49 和 50 的输出,在 numbers.dat 文件中,otput 仍然只是用逗号分隔的奇数。我无法理解我的代码究竟要更改什么:(
回答by Bharat Sinha
For the correct number to print you should change
要打印正确的数字,您应该更改
Even number loop:
偶数循环:
//This for loop handles adding all of the numbers together
for(int i = 2; i <=100; i += 2) {
writer.write("" + i + ", ");
}
Odd number loop:
奇数循环:
//This for loop is identical to the previous one, except for odd numbers
for(int i = 1; i < 100; i += 2) {
writer2.write("" + i + ", ");
}
And replace your following statement:
并替换您的以下声明:
System.out.println(reader.read());
with
和
System.out.println(reader.readLine());
and you should be done.
你应该完成。
EDIT
编辑
public class textFileIO {
public static void main(String[] args) throws Exception {
//Clear the contents of numbers.dat if already exists and populated
File fileOne = new File("numbers.dat");
fileOne.delete();
File newFile = new File("numbers.dat");
newFile.createNewFile();
//Create writer object
PrintWriter writer = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is even, write to file
if (i % 2 == 0) {
writer.print(i + ",");
}
}
//Close writer object.
writer.close();
//Read from file
FileInputStream fileStream = new FileInputStream("numbers.dat");
DataInputStream in = new DataInputStream(fileStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//Print line
System.out.println(reader.readLine());
reader.close();
//Write all odd numbers to file
PrintWriter writer2 = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is odd, write to file
if (i % 2 == 1) {
writer2.print(i + ",");
}
}
writer2.close();
//Read from file
FileInputStream fileStream2 = new FileInputStream("numbers.dat");
DataInputStream in2 = new DataInputStream(fileStream2);
BufferedReader reader2 = new BufferedReader(new InputStreamReader(in2));
//Print line
System.out.println(reader2.readLine());
reader.close();
}
}
This worked perfectly for me and here is the output...
这对我来说非常有效,这是输出......
2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100, 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,
2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50, 52、54、56、58、60、62、64、66、68、70、72、74、76、78、80、82、84、86、88、90、92、94、96、98、100、1、 3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51, 53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,
回答by hythlodayr
A few things:
一些东西:
For the second writer (writer2), you need to pass in a "true" value in the FileWriter constructor. Otherwise, it will simply overwrite outfile with new content (see FileWriter Constructor)
PrintWriter writer2 = new PrintWriter(new FileWriter("numbers.dat", true));
As Govan mentioned, you're not closing writer2. This is why your file is blank. If you call writer2.close, the BufferedWriter's "flush" method gets called. "flush" is what actually forces the writer to write data into the file (When to Flush a BufferedWriter).
As Bharat mentioned, you should re-write your loops to use the "i" variable to write, not sumEven. The way you sumEven is written, you'll get the following:
i=1, sumEven = sumEven + i + 1 = 0 + 1 + 1 = 2
i=3, sumEven = sumEven + i + 1 = 2 + 3 + 1 = 6
i=5, sumEven = sumEven + i + 1 = 6 + 5 + 1 = 12
...
对于第二个 writer (writer2),您需要在 FileWriter 构造函数中传入一个“true”值。否则,它将简单地用新内容覆盖输出文件(请参阅FileWriter Constructor)
PrintWriter writer2 = new PrintWriter(new FileWriter("numbers.dat" , true));
正如戈文所提到的,你并没有关闭 writer2。这就是为什么你的文件是空白的。如果您调用 writer2.close,将调用 BufferedWriter 的“flush”方法。“刷新”实际上是强制写入器将数据写入文件(何时刷新 BufferedWriter)。
正如 Bharat 所提到的,您应该重新编写循环以使用“i”变量来编写,而不是 sumEven。你 sumEven 的写法,你会得到以下结果:
i=1, sumEven = sumEven + i + 1 = 0 + 1 + 1 = 2
i=3, sumEven = sumEven + i + 1 = 2 + 3 + 1 = 6
i=5, sumEven = sumEven + i + 1 = 6 + 5 + 1 = 12
...
回答by Govan
your first loop can be like this
你的第一个循环可以是这样的
for (i = 0; i < 100 ; i+2)
{
if (i != 0) {
writer.print(", ");
}
writer.print(i+2);
}
the second shall be like this
第二个应该是这样的
for (i = 0; i < 100 ; i+2)
{
writer.print( ", " +(i+1));
}
Otherwise you have to go an extra comma on the end of line!
否则你必须在行尾多加一个逗号!
回答by Aardvocate Akintayo Olusegun
I made a couple of changes to your code.
我对您的代码进行了一些更改。
First you don't need two writers, neither do you need two readers.
首先,您不需要两个作家,也不需要两个读者。
Your single writer can write both even and odd numbers since you are only writing to one file. The scenario where I will consider two writers is if your are writing an odd file and an even file separately, concurrently.
由于您只写入一个文件,因此您的单个写入器可以写入偶数和奇数。我将考虑两个作者的情况是,如果您同时分别编写一个奇数文件和一个偶数文件。
Anyway, I just commented out the fluff stuff. If you delete all the comments, the code should be simpler, works and most especially more readable.
无论如何,我只是注释掉了绒毛的东西。如果删除所有注释,代码应该更简单、有效,尤其是更具可读性。
import java.io.*;
import java.util.*;
public class TextFileIO {
public static void main(String[] args) throws Exception {
//Clear the contents of numbers.dat if already exists and populated
File fileOne = new File("numbers.dat");
fileOne.delete();
File newFile = new File("numbers.dat");
newFile.createNewFile();
//Create writer object
PrintWriter writer = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is even, write to file
if (i % 2 == 0) {
writer.print(i + ",");
}
}
//Close writer object.
//writer.close();
//Read from file
//FileInputStream fileStream = new FileInputStream("numbers.dat");
//DataInputStream in = new DataInputStream(fileStream);
//BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//Print line
//System.out.println(reader.readLine());
//reader.close();
//Write all odd numbers to file
//PrintWriter writer2 = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is odd, write to file
if (i % 2 == 1) {
writer.print(i + ",");
}
}
writer.close();
//Read from file
FileInputStream fileStream2 = new FileInputStream("numbers.dat");
DataInputStream in2 = new DataInputStream(fileStream2);
BufferedReader reader2 = new BufferedReader(new InputStreamReader(in2));
//Print line
System.out.println(reader2.readLine());
reader2.close();
}
}
Cleaning up the code a bit, you get the below
稍微清理一下代码,您会得到以下内容
import java.io.*;
import java.util.*;
public class TextFileIO {
public static void main(String[] args) throws Exception {
//Clear the contents of numbers.dat if already exists and populated
File fileOne = new File("numbers.dat");
fileOne.delete();
File newFile = new File("numbers.dat");
newFile.createNewFile();
//Create writer object
PrintWriter writer = new PrintWriter(new FileWriter("numbers.dat"));
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is even, write to file
if (i % 2 == 0) {
writer.print(i + ",");
}
}
//Loop from 1 to 100
for (int i = 1; i <= 100; i++) {
//If number is odd, write to file
if (i % 2 == 1) {
writer.print(i + ",");
}
}
writer.close();
//Read from file
FileInputStream fileStream = new FileInputStream("numbers.dat");
DataInputStream in = new DataInputStream(fileStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//Print line
System.out.println(reader.readLine());
reader.close();
}
}