繁体   English   中英

从文件加载数组

[英]Loading an Array from a File

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

编写一个方法,从您创建的名为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");

谢谢。

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

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

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

见文件在这里

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

如何使用Java逐行读取大型文本文件?

获得文件的一行后,就可以将其添加到数组中。

看一下Scanner的javadoc: http//docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

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

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

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

/**
 * 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[] {};
}
 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]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM