【问题标题】:Replacing the values of columns in text file替换文本文件中列的值
【发布时间】:2013-04-25 05:53:08
【问题描述】:

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

col1 col2 col3 ----- ----- ----- 一个WM S2 B JK S3 C ZO S2

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

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

这个用java怎么写?

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 谢谢重播,嗯,我说的放两张表是什么意思,意思是把值A换成0,把B换成1,一直到最后col3 中的值。这是 S2 将被替换为 6。这些表只是示例,未知的行和列的实际数量。我想单独阅读每个列,但似乎有点难以解决。如果你能提供帮助,我将不胜感激我
    【解决方案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);
     }
    

    【讨论】:

      猜你喜欢
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      相关资源
      最近更新 更多