簡體   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