Java读取文件到一个ArrayList?
如何将文件的内容读入Java中的ArrayList<String>
?
这里是文件内容:
cat house dog . . .
只要将每个单词读入ArrayList
。
这个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()
。
与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"));
您可以使用:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
来源: Java API 7.0
在Java 8中,您可以使用stream和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); }
或者作为一个function,包括从文件系统加载文件:
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();
例如,你可以这样做(完整的代码,例外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(); } }
//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; }
这是一个对我来说工作得很好的解决scheme:
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]+") );
这是一个完整的程序示例:
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; } }
添加此代码以对文本文件中的数据进行sorting。 Collections.sort(list);