[英]save input from text file to array
如何將文本文件內容保存到不同的數組?
我的文本文件內容是這樣的;
12 14 16 18 13 17 14 18 10 23
pic1 pic2 pic3 pic4 pic5 pic6 pic7 pic8 pic9 pic10
left right top left right right top top left right
100 200 300 400 500 600 700 800 900 1000
如何將每一行保存到不同的數組? 例如
line 1 will be saved in an array1
line 2 will be saved in an array2
line 3 will be saved in an array3
line 4 will be saved in an array4
解決方案1
List<String[]> arrays = new ArrayList<String[]>(); //You need an array list of arrays since you dont know how many lines does the text file has
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
String arr[] = str.split(" ");
if(arr.length>0) arrays.add(arr);
}
in.close();
} catch (IOException e) {
}
最后,數組將包含每個數組。 在您的示例中arrays.length()==4
迭代數組:
for( String[] myarr : arrays){
//Do something with myarr
}
解決方案2:我不認為這是一個好主意,但如果你確定文件總是包含4行,你可以這樣做
String arr1[];
String arr2[];
String arr3[];
String arr4[];
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
str = in.readLine();
arr1[] = str.split(" ");
str = in.readLine();
arr2[] = str.split(" ");
str = in.readLine();
arr3[] = str.split(" ");
str = in.readLine();
arr4[] = str.split(" ");
in.close();
} catch (IOException e) {
}
看看String []拆分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.