将偶数和奇数写入dat文件

时间:2012-08-11 11:50:27

标签: java file-io

我已经开始学习Java,并且遇到了一个简单程序的问题,该程序应该将一些内容写入numbers.dat文件。

我面临两个问题:

  1. 我得到的输出如下:

      

    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,1402,1482,1560,1640,1722,1806,1892,1980,2070,2162,2256,2352,2450 ,2550 ......

    应该是:

    对于偶数:

      

    2,4,6,8,10,12,14,......,98100

    对于奇数:

      

    2,4,6,8,10,12,14,......,98,100,1,3,5,7,9,......。.97,99

  2. 我的第二个问题是输出没有写入numbers.dat文件!这一切都是空白的。

    请有人帮我这个。我真的很感激

  3. 我试图解决的书中的问题是:

      

    编写一个名为TextFileIO.java的程序来创建一个名为numbers.dat的文件。然后创建一个算法,将所有偶数编号的整数从1写入100,用逗号分隔。

         

    创建文件后,关闭并重新打开文件并将结果显示在屏幕上。显示结果后,将奇数整数从1添加到100,用逗号分隔到文件末尾。重新打开文件并显示结果。该文件的内容应为1到100之间的偶数,用逗号分隔,后跟以逗号分隔的1到100的奇数。该程序的输出类似于以下内容:

         

    2,4,6,8,10,12,14,......,98100

         

    2,4,6,8,10,12,14,......,98,100,1,3,5,7,9,...... ..97,99

    以下是我到目前为止尝试过的代码:

    textFileIO.java

    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) {
    
            }
        }
    }
    

    修改2

    我更改了代码,这是我最新的代码。我还有问题。 控制台输出屏幕显示49和50作为out put annnd我的numbers.dat文件现在只显示逗号分隔列表f奇数...我现在做错了什么? :(请帮帮我!

    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();
            }
    
    
        }
    

    编辑3:伙计我仍然无法获得所需的输出。我仍然在控制台中获得49和50的输出,而在numbers.dat文件中,输出仍然是由逗号分隔的ONLy奇数。我无法理解我的代码究竟要改变什么:(

4 个答案:

答案 0 :(得分:2)

要打印正确的号码,您应该更改

偶数循环:

//This for loop handles adding all of the numbers together
for(int i = 2; i <=100; i += 2) {
writer.write("" + i + ", ");
}

奇数圈:

//This for loop is identical to the previous one, except for odd numbers
for(int i = 1; i < 100; i += 2) {
writer2.write("" + i + ", ");
}

并替换以下声明:

System.out.println(reader.read());

System.out.println(reader.readLine());

你应该完成。

修改

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();
    }
}

这对我来说非常合适,这是输出......

  

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,

答案 1 :(得分:1)

一些事情:

  1. 对于第二个writer(writer2),您需要在FileWriter构造函数中传入一个“true”值。否则,它只会用新内容覆盖outfile(参见FileWriter Constructor

    PrintWriter writer2 = new PrintWriter(new FileWriter(“numbers.dat”,true ));

  2. 正如Govan所说,你不是在关闭writer2。这就是您的文件为空的原因。如果调用writer2.close,则调用BufferedWriter的“flush”方法。 “flush”实际上是强制写入者将数据写入文件(When to Flush a BufferedWriter)。

  3. 正如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

    ...

答案 2 :(得分:1)

你的第一个循环可以是这样的

for (i = 0; i < 100 ; i+2)
{ 
   if (i != 0) {
    writer.print(", ");
   } 
    writer.print(i+2);
}   

第二个应该是这样的

for (i = 0; i < 100 ; i+2)
{ 
    writer.print( ", " +(i+1));
}   

否则你必须在行尾添加额外的逗号!

答案 3 :(得分:1)

我对您的代码进行了一些更改。

首先你不需要两个作家,也不需要两个读者。

由于您只写一个文件,因此您的单个编写者可以编写偶数和奇数。我将考虑两个编写器的情况是,如果您同时单独编写奇数文件和偶数文件。

无论如何,我只是评论了绒毛的东西。如果删除所有注释,代码应该更简单,更有效,最可读。

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();
        }


    }

稍微清理一下代码,你得到以下内容

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();
    }
}