2012-05-04 271 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()进行拆分。