替换文本文件中列的值

时间:2013-04-25 05:53:09

标签: java

我有一个包含不同列的文件,每列的值都是字符串标签

col1    col2   col3
-----   -----  -----
A       WM     S2
B       JK     S3
C       ZO     S2

如果我想将每个值的值替换为数字,我将使用以下格式的表格

col1    col2   col3
-----   -----  -----
0       3       6
1       4       7
2       5       6

如何在java中写这个?

2 个答案:

答案 0 :(得分:0)

您可以使用java.util.Scanner,因为.next()会同等对待数字和文字

final Scanner scanner = new Scanner(new File("path_to_file"));
final List<String[]> list = new ArrayList<String[]>();

try {
    // skip 2 first lines
    if (scanner.hasNextLine())
        scanner.nextLine();
    if (scanner.hasNextLine())
        scanner.nextLine();

    while (scanner.hasNextLine()) {
        final String[] line = new String[3];
        for (int i = 0; i < 3 && scanner.hasNext(); i++) {
            line[i] = scanner.next();
        }
        list.add(line);
        scanner.nextLine();
    }
} finally {
    scanner.close();
}

// the file content is in "list" variable now, so you can modify and save back to file

答案 1 :(得分:-2)

因为你不完全知道行数

您执行以下操作 - 读取所有行(这将给你行数)rowsNo - 你重写了你的桌子。

  for (int row=0; row<rowsNo; row++) {
  String rowStr = "";  
  for (int col=0; col<colsNo; col++)  
     rowStr += row+col*colsNo;
  System.out.println(rowStr);
 }