将文件读入数组列表?

如何用 Java 将文件内容读入 ArrayList<String>

以下是文件内容:

cat
house
dog
.
.
.
366236 次浏览
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();

这段 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()

例如,您可以这样做(带有异常处理的完整代码) :

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();
}
}

(法语)的一句俏皮话:

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"));

下面是一个完整的程序示例:

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;
}
}

你可使用:

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

资料来源: Java API 7.0

//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;
}

爪哇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;
}

这里有一个对我非常有效的解决方案:

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]+")
);

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

我见过的最简单的形式就是..。

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

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

如果您需要快速读取数据,请使用老的 BufferedReaderFileReader 示例

扫描仪要慢得多,花了我138毫秒

漂亮的 Java8 Files.lines (...)是最慢的版本,花了我 ~ 388ms。

    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 (sc.next ()) ; } * 上面的代码负责在 add 函数 */的帮助下在数组表中添加数据