2012-05-04 269 views
1

我有.txt文件,我想從它讀取到char數組。Java /從.txt文件讀取

我有問題,在.txt文件我有:

1 a 

3 b 

2 c 

這意味着一個[1] = 'A',A [3] = 'B',A [2] =」 C'。

如何在讀取文件時忽略空格並考慮新行?由於

+0

你是指'char [] a'或'String [] a'? – dacwe

+0

@dacwe:char [] a –

+0

值也可以是字母字符,或只有整數? – sp00m

回答

1

我會建議你使用Map這個,而不是因爲它是更適合這類問題:

public static void main(String[] args) { 

    Scanner s = new Scanner("1 a 3 b 2 c"); // or new File(...) 

    TreeMap<Integer, Character> map = new TreeMap<Integer, Character>(); 

    while (s.hasNextInt()) 
     map.put(s.nextInt(), s.next().charAt(0)); 
} 

如果你想轉換的TreeMapchar[]你可以做以下內容:

char[] a = new char[map.lastKey() + 1]; 

for (Entry<Integer, Character> entry : map.entrySet()) 
    a[entry.getKey()] = entry.getValue(); 

注:

  • 此解決方案不具有負指數
  • 工作只對「第一」字符,如果超過一個
0

這可能比較容易使用Scanner

ArrayList<String> a = new ArrayList<String>(); 
Scanner s = new Scanner(yourFile); 
while(s.hasNextInt()) { 
    int i = s.nextInt(); 
    String n = s.next(); 
    a.add(n); 
} 

當然,這大膽地假設正確的輸入;你應該更偏執。如果您需要專門處理每條線,則可以使用hasNextLine()nextLine(),然後使用String類中的split()進行拆分。