[英]Storing String from file in an ArrayList object?
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Cities {
public static void main(String[] args) throws IOException {
String filename;
System.out.println("Enter the file name : ");
Scanner kb = new Scanner(System.in);
filename = kb.next();
//Check if file exists
File f = new File(filename);
if(f.exists()){
//Read file
File myFile = new File(filename);
Scanner inputFile = new Scanner(myFile);
//Create arraylist object
ArrayList<String> list = new ArrayList<String>();
String cit;
while(inputFile.hasNext()){
cit = inputFile.toString();
list.add(inputFile.toString());
}
System.out.println(list);
}else{
System.out.println("File not found!");
}
}
}
I am trying to read a file and add the contents to an arraylist
object ( .txt
file contains strings), but I am totally lost. 我正在尝试读取文件并将内容添加到
arraylist
对象( .txt
文件包含字符串),但我完全迷失了。 Any advice? 有什么建议?
You should read the file one line by one line and store it to the list. 您应该逐行读取文件并将其存储到列表中。
Here is the code you should replace your while (inputFile.hasNext())
: 这是你应该替换你的代码
while (inputFile.hasNext())
:
Scanner input = null;
try
{
ArrayList<String> list = new ArrayList<String>();
input = new Scanner( new File("") );
while ( input.hasNext() )
list.add( input.nextLine() );
}
finally
{
if ( input != null )
input.close();
}
And you should close the Scanner
after reading the file. 您应该在阅读文件后关闭
Scanner
。
If you're using Java 7+, then you can use the Files#readAllLines()
to do this task for you, instead of you writing a for
or a while
loop yourself to read the file line-by-line. 如果您使用的是Java 7+,则可以使用
Files#readAllLines()
为您执行此任务,而不是自己编写for
或while
循环来逐行读取文件。
File f = new File(filename); // The file from which input is to be read.
ArrayList<String> list = null; // the list into which the lines are to be read
try {
list = Files.readAllLines(f.toPath(), Charset.defaultCharset());
} catch (IOException e) {
// Error, do something
}
You can do it in one single line with Guava. 你可以用Guava一行完成。
final List<String> lines = Files.readLines(new File("path"), Charsets.UTF8);
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset) http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File,java.nio.charset.Charset)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.