首页 > 解决方案 > 在 Java 中读取格式化文本

问题描述

我正在尝试用 Java 读取格式化文件,我曾经在 C 中做得很好,但这里没有线索。示例行是:

一个“0”公元前

我想将 A 和 0 作为两个单独的字符串,将 [B, C] 作为字符串 ArrayList 中的两个字符串。

无论如何都可以修改行格式,例如添加逗号

A'0' B、C、D...

关于如何拆分这个的任何想法?在 C 中工作时,我曾经使用 fseek、fread 等来完成它

标签: javafileformat

解决方案


请尝试以下代码: 这里的想法是使用 Java“扫描仪”类。这将逐行读取文件,直到到达文件末尾。

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();
    }
  }
}

推荐阅读