Home > database >  How can I read int and string (two columns) from file in Java?
How can I read int and string (two columns) from file in Java?

Time:03-03

I have a file with two columns:

10 Mike
7 Jhon
21 Charles

and I wanted to read these values. Is there an easy wy to do this? I know in C it's simple, but it seems it's not in Java.

CodePudding user response:

There are multiple ways you can do it. If you use Java 8 , you can do:

Files.readAllLines(...)
    .forEach(line -> {
       String[] splitted = line.split("\\s ");
       //now you can access your values splitted[0] and splitted[1]
    });

You can convert the string values to the type you want afterwards.

You can also use libraries for more complex scenarios. Some common ones are:

  1. Apache Commons CSV https://www.baeldung.com/apache-commons-csv
  2. Jackson CSV https://dirask.com/posts/Java-how-to-read-CSV-file-into-java-object-using-Jackson-CSV-library-complex-example-with-BigDecimal-and-enum-x1Rm7j

CodePudding user response:

Use a Scanner object to Input data from a text file

Instantiate the object:

Scanner scan = new Scanner(new File("example.txt"));

Call Method for Next Integer in the File

int n = scan.nextInt();

Call Method for next String

String s = scan.next();
  • Related