J
J
JML962022-03-14 22:31:23
Java
JML96, 2022-03-14 22:31:23

How to correctly read from a file and write numbers to a file (I/O)?

Write 100 positive and 100 negative random integers alternately to the numbers file, listing them separated by a space. Then read this file and scatter the read numbers into 2 files: positive_numbers and negative_numbers, with positive and negative numbers, respectively.
What is the reason for not writing positive numbers to the numbers_positive file?
And how can one write negative ones in the same way?

public static void main(String[] args) {
        File file = new File("D:/numbers.txt");

        try (FileWriter fw = new FileWriter(file, true)) {
            for (int i = 0; i <= 100; i++) {
                fw.write(" " + getRandomNumber(1, 100));
            }
            for (int i = 0; i <= 100; i++) {
                fw.write(" " + getRandomNumber(-1, -100));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try (FileReader fr = new FileReader("D:/numbers.txt");
             FileWriter fwnp = new FileWriter("D:/numbers_positive.txt");
             FileWriter fwnn = new FileWriter("D:/numbers_negative.txt")) {
            int c = fr.read();
            while (c > 0) {
                c = fr.read();
                fwnp.write(c);
                fwnp.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static int getRandomNumber(int a, int b) {
        if (b < a)
            return getRandomNumber(b, a);
        return a + (int) ((1 + b - a) * Math.random());
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2022-03-14
@xez

The .read() method reads one character.
Not one number, not one line. One character.
Try using Scanner. It has a suitable .nextInt() method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question