I have .txt file, and I want to read from it to char array.
I have problem, in the .txt file I have:
1 a
3 b
2 c
which mean that a[1]='a', a[3]='b', a[2]='c'.
How in reading the file, I ignore from spaces, and consider the new lines? Thanks
I have .txt file, and I want to read from it to char array.
I have problem, in the .txt file I have:
1 a
3 b
2 c
which mean that a[1]='a', a[3]='b', a[2]='c'.
How in reading the file, I ignore from spaces, and consider the new lines? Thanks
我建议您改用 a 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));
}
如果您想将其转换TreeMap为char[]您可以执行以下操作:
char[] a = new char[map.lastKey() + 1];
for (Entry<Integer, Character> entry : map.entrySet())
a[entry.getKey()] = entry.getValue();
笔记:
使用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()and nextLine(),然后使用split()String 类中的分割行。