[英]Read line by line java
I have a textfile which looks like this: 我有一个看起来像这样的文本文件:
1
2 3
4 5
6 7
I want to have 2 strings that are the values of same line. 我想有2个字符串,它们是同一行的值。 Example:
例:
String s1 will be 2, String s2 will be 3 字符串s1将为2,字符串s2将为3
I tried like this: 我这样尝试过:
File file = new File("e:\\read.txt");
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
while (ln.getLineNumber() == 0){
s=Integer.parseInt(ln.readLine());
System.out.println(s);
}
DisjointSetLinkedList dsj=new DisjointSetLinkedList();
while(ln.getLineNumber()>0)
{
String [] tokens = ln.readLine().split(" ");
s1=tokens[0];
System.out.println( s1);
}
I have to make union between 2 strings, that are on the same line: 我必须在同一行的2个字符串之间建立并集:
Change your second loop to : 将第二个循环更改为:
String line = null;
while ((line = ln.readLine()) != null) {
String[] tokens = line.split(" ");
String s1 = tokens[0];
String s2 = tokens[1];
System.out.println("s1 = " + s1 + " s2 = " + s2);
}
Otherwise you'll have NullPointerException
when trying to access last line read with ln.readLine()
. 否则,当尝试访问使用
ln.readLine()
读取的最后一行时,将出现NullPointerException
。
You also don't need while loop
to read first line, just read it once. 您也不需要
while loop
来读取第一行,只需读取一次即可。
I think sth like that is easier: 我认为这样更容易:
try {
File file = new File("numbers.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine())!= null) {
String[] tokens = line.split("\\s");
System.out.println(Arrays.toString(tokens));
}
} catch (Exception e) {
e.printStackTrace();
}
if you have token[0] as the entire first row you can union like this 如果您将token [0]作为整个第一行,则可以像这样进行合并
for(int i=2; i<token.length;i+2)
System.out.println("UNION: "+Union(token[i-2], token[i]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.