从文件加载数组

时间:2013-11-24 10:05:30

标签: java arrays methods

我正在按照以下说明进行作业,

编写一个方法,该方法将从您创建的名为floats.txt的文件中加载浮点数数组,然后返回该数组。假设文件中的第一个值保存数组的大小。一定要打电话给你的方法。

我创建了以下文件,标题为floats.txt

5
  4.3
  2.4
  4.2
  1.5
  7.3

我从未编写过返回数组的方法,也从未创建过从文件中读取的数组。不要求任何人以任何方式为我编写程序,但会感谢一些建议让我开始。我编写了方法标题,如下所示,

  public static double[] floatingFile() throws IOException {
  Scanner fin = new Scanner(new File"floats.txt");

感谢。

6 个答案:

答案 0 :(得分:2)

对于Java 7,我会使用1行代码:

List<String> lines = Files.readAllLines(Paths.get("floats.txt"), StandardCharsets.UTF_8);
  

从文件中读取所有行。此方法可确保在读取所有字节或抛出I / O错误或其他运行时异常时关闭文件。使用指定的字符集将文件中的字节解码为字符。

请参阅文档here

答案 1 :(得分:0)

你需要将文件读入内存,你可以按照以下内容逐行完成:

How to read a large text file line by line using Java?

一旦你有一行文件,你可以将它添加到你的数组。

答案 2 :(得分:0)

查看扫描程序的javadoc:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

有一些方法,如Scanner.next(),它将返回文件中的下一个值。

答案 3 :(得分:0)

您可以打开文件并逐个读取元素,同时将它们存储在每个数组元素中,直到它达到null。 你熟悉ArrayList吗?

答案 4 :(得分:0)

我会将文件的路径传递给您的构造函数(如下所示),您仍然需要添加一两件事......例如,请参阅here

/**
 * Read in a file containing floating point numbers and
 * return them as an array.
 * 
 * @param filePath
 *          The path to the file to read.
 * @return Any double(s) read as an array.
 */
public static double[] floatingFile(String filePath) {
  Scanner fin = null;
  try {
    // Open the file at filePath.
    fin = new Scanner(new File(filePath));
    // first read the size
    int advSize = 0;
    if (fin.hasNextInt()) {
      // read in an int.
      advSize = // DO SOMETHING TO READ AN INT.
    }
    // construct a dynamic list to hold the Double(s).
    List<Double> al = new ArrayList<Double>(advSize);
    // while there are Double(s) to read.
    while (fin.hasNextDouble()) {
      // read in a double.
      double d = // DO SOMETHING TO READ A DOUBLE.
      al.add(d);
    }
    // Construct the return array.
    double[] ret = new double[al.size()];
    for (int i = 0; i < ret.length; i++) {
      ret[i] = al.get(i);
    }
    return ret;
  } catch (FileNotFoundException ignored) {
  } finally {
    if (fin != null) {
      // close our file reader.
      fin.close();
    }
  }
  // Return the empty array.
  return new double[] {};
}

答案 5 :(得分:0)

 public float[] readLines(String <your filename>){ //in the try block
    FileReader fileReader = new FileReader(filename);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    List<float> arrFloat = new ArrayList<float>();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
    }
    bufferedReader.close();
    return arrFloat.toArray(new floatArray[arrFloat]);
}