Home > Blockchain >  How to use both string and int in BufferReader?
How to use both string and int in BufferReader?

Time:12-19

I'm wondering if I can use BufferedReader with both string and integer, and what's wrong with my code?

import java.io.*;

public class Main {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        try {
            var writer = new BufferedWriter(new FileWriter("test.txt"));
            writer.write("hello");
            writer.write("\n welcome");
            for (int num : nums) {
                writer.write(num   "\n");
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        
        try {
            BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
            String line = reader.readLine();
            int num = Integer.parseInt(reader.readLine());
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I want to read both int and string that have been written in the above method by JUST using BufferedReader

CodePudding user response:

You can try to check earlier, if given string is a number, e.g.:

private static boolean isNumeric(String str) {
    return str != null && str.matches("[0-9.] ");
}

and then, if isNumeric(line) is true, assign it as integer.

CodePudding user response:

First you are missing a few semicolons(;) on the line where you are creating the nums array and on the line you are writing the string '\n welcome'.

Secondly when writing to you file the first 2 lines are string values, so when you try to use parseInt on the second line it throws a NumberFormatException.

  • Related