我如何从文件中读取到一个数组 [英] How do I read from a File to an array
本文介绍了我如何从文件中读取到一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从文件到一个数组阅读。我尝试了两种不同的风格和两者都不能正常工作。下面是两种风格。
I am trying to read from a file to an array. I tried two different styles and both aren't working. Below are the two styles.
public class FileRead {
int i;
String a[] = new String[2];
public void read() throws FileNotFoundException {
//Z means: "The end of the input but for the final terminator, if any"
a[i] = new Scanner(new File("C:\\Users\\nnanna\\Documents\\login.txt")).useDelimiter("\\n").next();
for(i=0; i<=a.length; i++){
System.out.println("" + a[i]);
}
}
public static void main(String args[]) throws FileNotFoundException{
new FileRead().read();
}
}
样式2
public class FileReadExample {
private int j = 0;
String path = null;
public void fileRead(File file){
StringBuilder attachPhoneNumber = new StringBuilder();
try{
FileReader read = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(read);
while((path = bufferedReader.readLine()) != null){
String a[] = new String[3];
a[j] = path;
j++;
System.out.println(path);
System.out.println(a[j]);
}
bufferedReader.close();
}catch(IOException exception){
exception.printStackTrace();
}
}
我需要它来读取字符串的每一行和每一行存放在数组中。但无论是作品。我怎么做呢?
I need it to read each line of string and store each line in an array. But neither works. How do I go about it?
推荐答案
请你帮个忙,并使用你提供此功能的库,例如。
Do yourself a favor and use a library that provides this functionality for you, e.g.
番石榴:
// one String per File
String data = Files.toString(file, Charsets.UTF_8);
// or one String per Line
List<String> data = Files.readLines(file, Charsets.UTF_8);
共享/ IO :
// one String per File
String data = FileUtils.readFileToString(file, "UTF-8");
// or one String per Line
List<String> data = FileUtils.readLines(file, "UTF-8");
这篇关于我如何从文件中读取到一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文