[英]Store text file content line by line into array
所有,我現在面臨着不知道將文本文件中的內容存儲到數組中的問題。 情況就像,文本文件內容:
abc1
xyz2
rxy3
我希望將它們逐行存儲到數組中,這可能嗎? 我的期望是這樣的:
arr[0] = abc1
arr[1] = xyz2
arr[2] = rxy3
我嘗試過這樣的事情,但似乎對我不起作用。 如果有人可以幫助我,真的非常感謝。
代碼是:
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
while((str = in.readLine()) != null){
String[] arr = str.split(" ");
for(int i=0 ; i<str.length() ; i++){
arr[i] = in.readLine();
}
}
我建議使用ArrayList
,它處理動態大小調整,而數組需要預先定義大小,您可能不知道。 您始終可以將列表重新轉換為數組。
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
最簡單的解決方案:
List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]);
請注意, java.nio.file.Files 從 1.7 開始
這應該有效,因為它使用 List ,因為您不知道文件中有多少行,而且它們以后可能會更改。
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null){
lines.add(str);
}
String[] linesArray = lines.toArray(new String[lines.size()]);
Files.lines(new File("/home/abdennour/path/to/file.txt").toPath()).collect(Collectors.toList());
你需要為你的情況做這樣的事情:-
int i = 0;
while((str = in.readLine()) != null){
arr[i] = str;
i++;
}
但請注意,應根據文件中的條目數正確聲明arr
。
建議:-使用List
代替(查看@Kevin Bowersox 的帖子)
List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));
試試這個:
String[] arr = new String[3];// if size is fixed otherwise use ArrayList.
int i=0;
while((str = in.readLine()) != null)
arr[i++] = str;
System.out.println(Arrays.toString(arr));
當您執行str = in.readLine()) != null
您將一行讀入str
變量,如果它不是 null 則執行while
塊。 你不需要再讀一遍arr[i] = in.readLine();
. 當您不知道輸入文件的確切大小(行數)時,也可以使用列表而不是數組。
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> output = new LinkedList<String>();
while((str = in.readLine()) != null){
output.add(str);
}
String[] arr = output.toArray(new String[output.size()]);
您可以使用此完整代碼解決您的問題。 有關更多詳細信息,您可以在appucoder.com上查看
class FileDemoTwo{
public static void main(String args[])throws Exception{
FileDemoTwo ob = new FileDemoTwo();
BufferedReader in = new BufferedReader(new FileReader("read.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str =in.readLine()) != null ){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
System.out.println(" "+Arrays.toString(stringArr));
}
}
建議為此使用 Apache IOUtils.readLines。 請參閱下面的鏈接。
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
您可以使用此代碼。 這工作得非常快!
public String[] loadFileToArray(String fileName) throws IOException {
String s = new String(Files.readAllBytes(Paths.get(fileName)));
return Arrays.stream(s.split("\n")).toArray(String[]::new);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.