Java将文件读入ArrayList?

发布于 2024-10-22 13:38:04 字数 139 浏览 5 评论 0原文

在 Java 中如何将文件内容读取到 ArrayList中?

以下是文件内容:

cat
house
dog
.
.
.

How do you read the contents of a file into an ArrayList<String> in Java?

Here are the file contents:

cat
house
dog
.
.
.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

自演自醉 2024-10-29 13:38:04

此 Java 代码读取每个单词并将其放入 ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();

如果需要,请使用 s.hasNextLine()s.nextLine()逐行阅读而不是逐字阅读。

This Java code reads in each word and puts it into the ArrayList:

Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
    list.add(s.next());
}
s.close();

Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

热风软妹 2024-10-29 13:38:04

您可以使用:

List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );

来源:Java API 7.0

You can use:

List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );

Source: Java API 7.0

晚风撩人 2024-10-29 13:38:04

commons-io 的单行:

List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");

番石榴

List<String> lines = 
     Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));

A one-liner with commons-io:

List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");

The same with guava:

List<String> lines = 
     Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
唐婉 2024-10-29 13:38:04

我发现的最简单的形式是......

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));

Simplest form I ever found is...

List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
你的心境我的脸 2024-10-29 13:38:04

Java 8中,您可以使用流和Files.lines

List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
    list = lines.collect(Collectors.toList());
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}

或者作为包括从文件系统加载文件的函数:

private List<String> loadFile() {
    List<String> list = null;
    URI uri = null;

    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }

    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}

In Java 8 you could use streams and Files.lines:

List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
    list = lines.collect(Collectors.toList());
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}

Or as a function including loading the file from the file system:

private List<String> loadFile() {
    List<String> list = null;
    URI uri = null;

    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }

    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}
蓝梦月影 2024-10-29 13:38:04
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
    words.add(line);
}
reader.close();
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
    words.add(line);
}
reader.close();
作妖 2024-10-29 13:38:04

例如,您可以通过这种方式执行此操作(带有异常处理的完整代码):

BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {   
    in = new BufferedReader(new FileReader("myfile.txt"));
    String str;
    while ((str = in.readLine()) != null) {
        myList.add(str);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        in.close();
    }
}

You can for example do this in this way (full code with exceptions handlig):

BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {   
    in = new BufferedReader(new FileReader("myfile.txt"));
    String str;
    while ((str = in.readLine()) != null) {
        myList.add(str);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (in != null) {
        in.close();
    }
}
决绝 2024-10-29 13:38:04
//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
    List<String> wives = new ArrayList<String>();
    try {
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        // for each line
        for(String line = input.readLine(); line != null; line = input.readLine()) {
            wives.add(line);
        }
        input.close();
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(1);
        return null;
    }
    return wives;
}
//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
    List<String> wives = new ArrayList<String>();
    try {
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        // for each line
        for(String line = input.readLine(); line != null; line = input.readLine()) {
            wives.add(line);
        }
        input.close();
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(1);
        return null;
    }
    return wives;
}
多情出卖 2024-10-29 13:38:04

这是一个对我来说非常有效的解决方案:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);

如果你不想空行,你也可以这样做:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);

Here's a solution that has worked pretty well for me:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);

If you don't want empty lines, you can also do:

List<String> lines = Arrays.asList(
    new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);
冰之心 2024-10-29 13:38:04

分享一些分析信息。通过简单的测试,读取大约 1180 行值需要多长时间。

如果您需要非常快地读取数据,请使用旧的 BufferedReader FileReader 示例。我花了大约 8 毫秒

扫描仪要慢得多。花了我大约 138 毫秒

不错的 Java 8 Files.lines(...) 是最慢的版本。我花了大约 388 毫秒。

To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.

If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms

The Scanner is much slower. Took me ~138ms

The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.

三生殊途 2024-10-29 13:38:04

这是一个完整的程序示例:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class X {
    public static void main(String[] args) {
    File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
        try{
            ArrayList<String> lines = get_arraylist_from_file(f);
            for(int x = 0; x < lines.size(); x++){
                System.out.println(lines.get(x));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("done");

    }
    public static ArrayList<String> get_arraylist_from_file(File f) 
        throws FileNotFoundException {
        Scanner s;
        ArrayList<String> list = new ArrayList<String>();
        s = new Scanner(f);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
        return list;
    }
}

Here is an entire program example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class X {
    public static void main(String[] args) {
    File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
        try{
            ArrayList<String> lines = get_arraylist_from_file(f);
            for(int x = 0; x < lines.size(); x++){
                System.out.println(lines.get(x));
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("done");

    }
    public static ArrayList<String> get_arraylist_from_file(File f) 
        throws FileNotFoundException {
        Scanner s;
        ArrayList<String> list = new ArrayList<String>();
        s = new Scanner(f);
        while (s.hasNext()) {
            list.add(s.next());
        }
        s.close();
        return list;
    }
}
冧九 2024-10-29 13:38:04
    Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/

    enter code here

ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/

while (scr.hasNext()){

列表.add(scr.next());
}
/*上面的代码负责在add函数的帮助下向arraylist添加数据*/

    Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/

    enter code here

ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/

while (scr.hasNext()){

list.add(scr.next());
}
/*above code is responsible for adding data in arraylist with the help of add function */

浅浅淡淡 2024-10-29 13:38:04

添加此代码对文本文件中的数据进行排序。
Collections.sort(列表);

Add this code to sort the data in text file.
Collections.sort(list);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文