2012-11-09 59 views
3

我是Java新手,所以請和我一起裸照。我正在嘗試讀取讀取包含以逗號分隔的記錄的文件的BufferedReader。我想分割兩個逗號之間的每個字符串(或記錄),去掉雙引號,並將每個字符串放入一個String數組的索引中。例如:Java - 將逗號分隔的記錄轉換爲字符串數組?

說我有文件中這一行:

( 「0001」, 「00203」, 「82409」(新行)

「0002」, 「00204」, 「82500」 (換行)

等)

我想把0001爲一個字符串數組[1], 欲00203到字符串數組[2], 等....

以下代碼遍歷該文件,將第二列中的所有記錄放入字符串數組[2]中。這意味着,在我執行下面的代碼後,如果我做System.out.println(arr [2]),它將打印00203和00204,而我想array [2]爲00203,array [5]爲00204.

這裏是我的代碼:

public String[] getArray(String source) { 

FileInputStream fileinput = new FileInputStream(source); 
GZIPInputStream gzip = new GZIPInputStream(fileinput); 
InputStreamReader inputstream = new InputStreamReader(gzip); 
BufferedReader bufr = new BufferedReader(inputstream); 

String str = null; 
String[] arr = null; 
    while((str = bufr.readLine()) != null) { 
    arr = str.replace("\"", "").split("\\s*,\\s*"); 
} 
return arr; 

任何幫助是極大的讚賞,謝謝。

回答

0

您是否嘗試過使用scanner類以及scanner.nextInt()。那麼你不需要做條紋。

Scanner s = new Scanner(inputstream); 
ArrayList<String> list = new ArrayList<String>(); 

while (s.hasNextInt()) 
    list.add(s.nextInt()); 
String[] arr = list.toArray(new String[list.size()]); 
0

很少有這些修改應該適合你。

public String[] getArray(String source) { 

FileInputStream fileinput = new FileInputStream(source); 
GZIPInputStream gzip = new GZIPInputStream(fileinput); 
InputStreamReader inputstream = new InputStreamReader(gzip); 
BufferedReader bufr = new BufferedReader(inputstream); 

String str = null; 
List<String> numbers = new LinkedList<String>; 

while((str = bufr.readLine()) != null) { 
    String[] localArr = str.split(","); 
    for(String intString : localArr){ 
    numbers.add(intString.trim()); 
    } 
} 
return arr; 
0

未測試:

arr = str.replaceAll("\"", "").replaceAll("(","").replaceAll(")","").split(","); 
1

Commons CSV是專爲您的具體使用情況。我們不要重新發明輪子,下面的代碼會導致GZipped CSV被分析爲字段和行,並且似乎是您正在嘗試執行的操作。

public String[][] getInfo() throws IOException { 
    final CSVParser parser = new CSVParser(new FileReader(new InputStreamReader(new GZIPInputStream(fileinput)), CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); 
    String[][] result = parser.nextRecord().values(); 
    return result; 
} 
相關問題