简体   繁体   English

从Java中的BufferReader读取字符字段

[英]Read field of chars from BufferReader in Java

how to read one line of chars in a field of chars in java? 如何在java的chars字段中读取一行chars?

private char[] w;
int i=0;

BufferedReader br = new BufferedReader(new FileReader("pathToFile..."));

char c = '-1';

while (c!='\n') {
    w[i++] = (char) br.read();
}

i got java.lang.NullPointerException 我有java.lang.NullPointerException

try this 尝试这个

 private char[] w;

 BufferedReader br = new BufferedReader(new FileReader("pathToFile..."));

 String s = null;
 // to iterate for each line in file
 while ((s = br.readLine()) !=  null ) {
    // this will store chars of line
    w = s.toCharArray();
   //TODO - do something based on w array

 }

You need to create an instance of the array (in Java, an array is an object -even if the array is of primitive types-) 您需要创建数组的实例(在Java中,数组是一个对象-即使该数组是原始类型-)

private char[] w = new char[numberBigEnough];

Note that I would rather use a more dynamic approach, vg using a StringBuilder instance. 请注意,我宁愿使用更动态的方法,即使用StringBuilder实例的vg。 That way you do not have to guess the line's length to specify the array dimensions. 这样,您不必猜测线的长度即可指定数组尺寸。

I personally would use an ArrayList here. 我个人将在这里使用ArrayList。

private List<Character> list = new ArrayList<Character>();

int i=0;

BufferedReader br = new BufferedReader(new FileReader("pathToFile..."));

char c = '-1';

while (c!='\n') {
    list.add((char) br.read());
}

Something like that. 这样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM