0

Hi I i'm trying to do a line by line reading in of a file in Java. For example I'd like to be able to do something like

//c code
while( fscanf(ptr, "%s %s %s",string1,string2,string3) == 3)
     printf("%s %s %s",string1,string2,string3);

Where I scan in every line in the file individually and store it in a variable.

I have started out by making a file object and finding the file. However I haven't found a function to be able to read input.

User9123
  • 675
  • 1
  • 8
  • 20

1 Answers1

3

Use line oriented input, split the lines and print the contents. That is, read each line, check if you have three tokens (end if you don't) and print them. Like,

Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    String[] tokens = line.split(" ");
    if (tokens.length != 3) {
        break;
    }
    System.out.printf("%s %s %s%n", tokens[0], tokens[1], tokens[2]);
}

Change System.in to a File to read from a file.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249