【问题标题】:Java text file input handlingJava 文本文件输入处理
【发布时间】:2014-10-13 22:27:24
【问题描述】:

我正在尝试从文本文件中读取数据,但我不太确定如何处理。

例如,如果我的数据在文本文件中如下所示:

2   
3   
(0 1 1)   
(0 2 3)

我想以下列方式保存这些值:

int a = 2;
int b = 3;   
int[][] c = new int[a][b];   
c[0][1] = 1   
c[0][2] = 3

括号中的数字是(行、列、值)我应该从数据中填写的二维数组。

我对输入流非常陌生。我必须做些什么才能让我的程序识别括号并且括号内的数据应该以不同的方式处理?

【问题讨论】:

  • 您需要做的就是使用 if 语句来确定通过流的下一个字符是否是括号。

标签: java inputstream bufferedreader


【解决方案1】:

首先,您需要初始化一个 Util 类,如 BufferedReader 或 Scanner,然后才能管理 txt 文件。

这是一段java代码的示例,它将txt文件中的所有数字都作为Double类型,然后将它们保存到一个列表中。

您可以对整数执行相同的操作,或者,只需使用所需的方法(检查 BufferedReader 和 Scanner javadocs)将每一行格式化为 String 以根据需要处理它们。

Scanner s = null;

s = new Scanner(new BufferedReader(new FileReader("YOUFILENAME.txt")));
        while (s.hasNext()) {
            if (s.hasNextDouble()) {
                \\\ YOURLIST.add (s.nextDouble ())
            } else {
                s.next();
            }   
        }
    } finally {
        s.close();
    }

要管理( 等字符,您可以使用String 类型的内置方法,例如split ()contains ()

另请参阅:http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点,这可能不是最优雅的,但类似这样的方法是可行的。我使用正则表达式来拆分括号。

    import java.util.Scanner;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.Arrays;
    
    public class Test {
        public static void main(String[] args) throws Exception {
          Scanner scan = new Scanner(System.in);
    
          // Read array dimensions
          String line = "";
    
          line = scan.hasNext() ? scan.nextLine() : null;
          if(line == null) {
            throw new Exception("Invalid input for 'a'");
          }
    
          int a = -1;
          try {
            a = Integer.valueOf(line);
          } catch(NumberFormatException e) { 
            System.out.println("Input is not a number: " + line);
            return;
          }
    
          int b = -1;
          line = scan.hasNext() ? scan.nextLine() : null;
          if(line == null) {
             throw new Exception("Invalid input for 'b'");
          }
          try {
            b = Integer.valueOf(line);
          } catch(NumberFormatException e) {
            System.out.println("Input is not a number: " + line);
            return;
          }
    
          if(a <= 0 || b <= 0) {
             throw new Exception("Array sizes should be larger than 0");
          }
          int array[][] = new int[a][b];
    
          // Gather array values
          while(scan.hasNext()) {
              line = scan.nextLine();
              if(line.charAt(0) == 'q') { break; } // 'q' to exit
              setArray(array, line);
          }
    
          // Print array
          for(int i=0; i < array.length; ++i) {
              System.out.println(Arrays.toString(array[i]));
          }
        }
    
        // Returns true on set success, false otherwise
        private static boolean setArray(int[][] array, String input) throws NumberFormatException {
          Pattern regex = Pattern.compile("\\((\\d*?) (\\d*?) (\\d*?)\\)");
          Matcher match = regex.matcher(input);
          if(match.matches() && match.groupCount() == 3) {
            int a = Integer.valueOf(match.group(1));
            int b = Integer.valueOf(match.group(2));
            int val = Integer.valueOf(match.group(3));
    
            // Check bounds
            if(a >= 0 && a < array.length && b >= 0 && b < array[0].length) {
                array[a][b] = val;
            }
            else { 
                return false;
            }
          }
          else {
            return false;
          }
          return true;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      相关资源
      最近更新 更多