Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

file - Read formatted text in Java

I'm trying to read a formatted file in Java, I used to do this pretty well in C but no clue here. The example line is:

A '0' B C

And I want to take A and 0 as two separated Strings and [B, C] as two Strings in a String ArrayList.

The line fomrat can be modified in anyway, for example adding commas

A '0' B, C, D...

Any idea on how to split this? I used to do it with fseek, fread, etc when working in C


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Plese try the below code: Idea here is to use the Java "Scanner" class. This will read the file by line until end of file is reached.

import java.io.File;  
import java.io.FileNotFoundException;  
import java.util.Scanner; 

public class fileReader {
  public static void main(String[] args) {
    try {
      File oFile = new File("myfile.txt");
      Scanner oScanner= new Scanner(oFile );
      while (oScanner.hasNextLine()) {
        String sLine = oScanner.nextLine(); //Next line will point to the next line on the file
        System.out.println(sLine ); //And any other operations on the line you would like to perform.
      }
      oScanner.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error Occurred");
      e.printStackTrace();
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...