2014-09-12 114 views
-5

Hi有一個名爲read.txt的文件,下面是文件中的數據。如何讀取文件並將數據存儲到字符串數組中

OS:B,A,Linux,Windows 7,Windows  
ARCH:32 Bit,64 Bit  
Browser:Chrome,Firefox,IE 

欲讀取該文件,並希望通過與
吐涎到數據轉換成字符串數組爲每列存儲「:」符號。

例如低於

String a[] = { "A","B","Linux", "Windows 7", "Windows" };  

String b[] = { "32 Bit", "64 Bit"};  

String c[] = { "Chrome", "Firefox" ,"IE"}; 
+5

太好了,請給它編碼:) – zerocool 2014-09-12 12:34:29

+0

你知道谷歌嗎?這是一個很好的搜索引擎,可以找到答案。當我谷歌搜索結果的第一個結果給了我一個完美的例子http://stackoverflow.com/questions/19844649/java-read-file-and-store-text-in-an-array。 – Matheno 2014-09-12 12:37:59

+0

你的代碼有什麼特別的問題嗎(你有你的代碼,對吧)? – Pshemo 2014-09-12 12:38:18

回答

5

甲方法是通過的ReadLine提取eachline。 一旦我們有一個包含該行的字符串,假設我們有一個單獨的「:」作爲分隔符來分割行。 提取數組的第二個元素,並做使用另一個分裂「」作爲分隔符

-1

下面是如何讀取一個文件:

BufferedReader reader = new BufferedReader("read.txt"); 
while((line = reader.readLine()) != null) 
{ 
    //process line 
} 

所以要接受你想要的結果:

ArrayList<String[]> arrays = new ArrayList<String[]>; 
BufferedReader reader = new BufferedReader("read.txt"); 
while((line = reader.readLine()) != null) 
{ 
    //process line 
    line = line.split(":")[1];//get the second part 
    arrays.add(line.split(","));//split at "," and save into the ArrayList 
} 
0

使用apache commons io ...

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import org.apache.commons.io.FileUtils; 

public class StackOverflowExample { 
    public static void main(String[] args) throws IOException{ 
     List<String> lines = FileUtils.readLines(null, "UTF-8"); 
     List<String[]> outLines = new ArrayList<String[]>(); 
     for(int i = 0; i < lines.size(); i++){ 
      String line = lines.get(i); 
      outLines.add(line.split("[:,]")); 

     } 
    } 
} 

正如已經指出的 - 你真的應該包括你正在使用的代碼的一個例子,而不是做你期望的代碼。如果你真的不知道該怎麼做,並且沒有代碼 - 我不確定這會有幫助。

相關問題