java 创建一个由 .txt 元素填充的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5278019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:22:42  来源:igfitidea点击:

Create an Array populating it by .txt elements

javaarraysfilefile-io

提问by Franky

I want to create an array, populating it while reading elements from a .txt file formatted like so:

我想创建一个数组,在从格式如下的 .txt 文件中读取元素时填充它:

item1
item2
item3

So the final result has to be an array like this:

所以最终结果必须是这样的数组:

String[] myArray = {item1, item2, item3}

Thanks in advance.

提前致谢。

采纳答案by Jo?o Silva

  1. Wrap a BufferedReaderaround a FileReaderso that you can easily read every line of the file;
  2. Store the lines in a List(assuming you don't know how many lines you are going to read);
  3. Convert the Listto an array using toArray.
  1. 将 a 包裹BufferedReader起来,FileReader以便您可以轻松读取文件的每一行;
  2. 将行存储在 a 中List(假设您不知道要阅读多少行);
  3. 使用 将 转换List为数组toArray

Simple implementation:

简单的实现:

public static void main(String[] args) throws IOException {
    List<String> lines = new ArrayList<String>();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("file.txt"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
    } finally {
        reader.close();
    }
    String[] array = lines.toArray();
}

回答by corsiKa

This smells like homework. If it is you should re-read your notes, and tell us what you've tried.

这闻起来像家庭作业。如果是,您应该重新阅读您的笔记,并告诉我们您的尝试。

Personally, I would use a Scanner (from java.util).

就个人而言,我会使用扫描仪(来自 java.util)。

import java.io.*;
import java.util.*;

public class Franky {
    public static void main(String[] args) {
        Scanner sc = new Scanner(new File("myfile.txt"));
        String[] items = new String[3]; // use ArrayList if you don't know how many
        int i = 0;
        while(sc.hasNextLine() && i < items.length) {
            items[i] = sc.nextLine();
            i++;
        }
    }

}