[英]Java reading a file into an ArrayList?
如何將文件的內容讀入 Java 中的ArrayList<String>
?
以下是文件內容:
cat
house
dog
.
.
.
此 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()
。
您可以使用:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
來源: Java API 7.0
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"));
我發現的最簡單的形式是...
List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
在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;
}
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();
例如,您可以以這種方式執行此操作(帶有異常處理的完整代碼):
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();
}
}
//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;
}
這是一個對我來說效果很好的解決方案:
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]+")
);
分享一些分析信息。 通過一個簡單的測試,讀取大約 1180 行值需要多長時間。
如果您需要非常快速地讀取數據,請使用舊的 BufferedReader FileReader 示例。 我花了~8ms
掃描儀要慢得多。 花了我~138ms
不錯的 Java 8 Files.lines(...) 是最慢的版本。 花了我大約 388 毫秒。
這是一個完整的程序示例:
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;
}
}
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()); } /*以上代碼負責通過add函數在arraylist中添加數據*/
添加此代碼以對文本文件中的數據進行排序。 Collections.sort(list);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.