【问题标题】:Reading Integers from text file and storing into array从文本文件中读取整数并存储到数组中
【发布时间】:2014-01-23 07:32:31
【问题描述】:

我整天都在用这个程序来读取整数的文本文件并将整数存储到数组中。我想我终于用下面的代码得到了解决方案。

但不幸的是.. 我必须使用 hasNextLine() 方法遍历文件。 然后使用 nextInt() 从文件中读取整数并将它们存储到数组中。 所以使用扫描仪构造函数,hasNextLine()、next() 和 nextInt() 方法。

然后使用try and catch 来确定哪些单词是整数,哪些不是,使用 InputMismatchException。文件中的空行也是一个例外? 问题是我没有使用 try 和 catch 和异常,因为我只是跳过了非整数。 另外,我使用的是 int 数组,所以我想在没有列表的情况下执行此操作。

      public static void main(String[] commandlineArgument) {
         Integer[] array = ReadFile4.readFileReturnIntegers(commandlineArgument[0]);
         ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
      }

      public static Integer[] readFileReturnIntegers(String filename) {
         Integer[] array = new Integer[1000];
         int i = 0;
        //connect to the file
         File file = new File(filename);
         Scanner inputFile = null;
         try {
            inputFile = new Scanner(file);
         } 
         //If file not found-error message
            catch (FileNotFoundException Exception) {
               System.out.println("File not found!");
            }
        //if connected, read file
         if (inputFile != null) {
         // loop through file for integers and store in array
            try {
               while (inputFile.hasNext()) {
                  if (inputFile.hasNextInt()) {
                     array[i] = inputFile.nextInt();
                     i++;
                  } 
                  else {
                     inputFile.next();
                  }
               }
            } 
            finally {
               inputFile.close();
            }
            System.out.println(i);
            for (int v = 0; v < i; v++) {
               System.out.println(array[v]);
            }
         }
         return array;
      }

      public static void printArrayAndIntegerCount(Integer[] array, String filename) {
      //print number of integers
      //print all integers that are stored in array
      }
   }

然后我将使用第二种方法打印所有内容,但我可以稍后再担心。 :o

文本文件的示例内容:

Name, Number
natto, 3
eggs, 12
shiitake, 1
negi, 1
garlic, 5
umeboshi, 1

样本输出目标:

number of integers in file "groceries.csv" = 6
    index = 0, element = 3
    index = 1, element = 12
    index = 2, element = 1
    index = 3, element = 1
    index = 4, element = 5
    index = 5, element = 1

对于类似的问题,我们深表歉意。我压力很大,甚至更多的是我做错了......我完全被困在这一点上:(

【问题讨论】:

  • 您应该再次阅读this 答案。尤其是末尾的printf
  • 数组的使用是绝对必要的吗?您最好使用List 实现(例如ArrayList):这样您就不必在开始时声明其大小,也不必管理放入其中的项目的索引。
  • 不幸的是我必须为这个程序使用一个数组。

标签: java arrays exception file-io


【解决方案1】:

您可以通过这种方式读取您的文件。

/* using Scanner */
public static Integer[] getIntsFromFileUsingScanner(String file) throws IOException {
    List<Integer> l = new ArrayList<Integer>();
    InputStream in = new FileInputStream(file);
    Scanner s = new Scanner(in);
    while(s.hasNext()) {
        try {
            Integer i = s.nextInt();
            l.add(i);
        } catch (InputMismatchException e) {
            s.next();
        }
    }
    in.close();
    return l.toArray(new Integer[l.size()]);
}

/* using BufferedReader */
public static Integer[] getIntsFromFile(String file) throws IOException {
    List<Integer> l = new ArrayList<Integer>();
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
        try {
            l.add(Integer.parseInt(line.split(",")[1]));
        } catch (NumberFormatException e) {
        }
    }
    return l.toArray(new Integer[l.size()]);
}    

还有你的代码:

  public static void main(String[] commandlineArgument) {
      Integer[] array = getIntsFromFileUsingScanner(commandlineArgument[0]);
      ReadFile4.printArrayAndIntegerCount(array, commandlineArgument[0]);
  }

【讨论】:

  • 嗨 marioosh,感谢您的意见。但我正在尝试使用 Scanner 构造函数、hasNextLine()、next() 和 nextInt() 方法进行循环。最重要的是对 inputmismatchexception 使用 try 和 catch。所以没有列表和 bufferedReader :(
【解决方案2】:

这是满足您的新要求的一种方法,

public static Integer[] readFileReturnIntegers(
    String filename) {
  Integer[] temp = new Integer[1000];
  int i = 0;
  // connect to the file
  File file = new File(filename);
  Scanner inputFile = null;
  try {
    inputFile = new Scanner(file);
  }
  // If file not found-error message
  catch (FileNotFoundException Exception) {
    System.out.println("File not found!");
  }
  // if connected, read file
  if (inputFile != null) {
    // loop through file for integers and store in array
    try {
      while (inputFile.hasNext()) {
        try {
          temp[i] = inputFile.nextInt();
          i++;
        } catch (InputMismatchException e) {
          inputFile.next();
        }
      }
    } finally {
      inputFile.close();
    }
    Integer[] array = new Integer[i];
    System.arraycopy(temp, 0, array, 0, i);
    return array;
  }
  return new Integer[] {};
}

public static void printArrayAndIntegerCount(
    Integer[] array, String filename) {
  System.out.printf(
      "number of integers in file \"%s\" = %d\n",
      filename, array.length);
  for (int i = 0; i < array.length; i++) {
    System.out.printf(
        "\tindex = %d, element = %d\n", i, array[i]);
  }
}

输出

number of integers in file "/home/efrisch/groceries.csv" = 6
    index = 0, element = 3
    index = 1, element = 12
    index = 2, element = 1
    index = 3, element = 1
    index = 4, element = 5
    index = 5, element = 1

【讨论】:

  • 我设法理解并正确完成了我的程序!非常感谢埃利奥特!从字面上拯救我从一个不眠之夜!我现在很开心!
【解决方案3】:

也许您可以通过我在下面发布的简短代码来解决此问题。

public static List<Integer> readInteger(String path) throws IOException {
    List<Integer> result = new ArrayList<Integer>();
    BufferedReader reader = new BufferedReader(new FileReader(path));
    String line = null;
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = null;
    line = reader.readLine();
    String input = null;
    while(line != null) {
        input = line.split(",")[1].trim();
        matcher = pattern.matcher(input);
        if(matcher.matches()) {
            result.add(Integer.valueOf(input));
        }
        line = reader.readLine();
    }
    reader.close();
    return result;
}

【讨论】:

    【解决方案4】:

    为下面的代码附上try catch:

    try
    {
       if (inputFile.hasNextInt()) {
            array[i] = inputFile.nextInt();
            i++;
       } 
       else {
            inputFile.next();
            }
    }catch(Exception e)
    {
        // handle the exception
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多