从文件中读取后无法保留该行。 [英] Not able to retain the line after reading it from a file.

查看:92
本文介绍了从文件中读取后无法保留该行。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用上面的代码来打印文件的行。问题是该线仅出现一毫秒。我的文件只包含一行长度为70,000的行,我希望将其拆分为某个子字符串,然后将其写入另一个文件,其中多行作为输出。我也尝试将读取字符串保存到while循环内的数组列表中。

 ArrayList ArrayList lis =  new  ArrayList()
lis.add(l)

此外,< pre lang =java> lis.size()

它显示字符串已成功复制到数组列表。

 lis.get( 0 )。length()

它显示列表中字符串的长度。但有些我怎么也不能在下面的代码和SysOut中读取字符串。

 System.out.println(lis.get( 0 ))

我不确定我在做什么错误。此外,我尝试上面的代码与一些其他文本文件有多行,它的工作原理。忽略上面代码中的错误(如果有的话),我在这里输入。谢谢!



我尝试过:



 public static void main(String args []){
String l = null;
try {
文件file = new File(sample.txt);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

int i = 0;
while((l = br.readLine())!= null){
System.out.println(l);
}
br.close();
}
catch(FileNotFoundException e){
System.out.println(找不到文件);
}
catch(IOException ex){

}
}

解决方案

  while ((l = br.readLine())!= null){



第一次调用它时,它会将该行读入变量 l ,然后显示该行。下次调用时,会到达文件末尾,因此 readLine 返回 null ,程序终止。



每次收到非空文本行时,你需要做更多的处理。


I am using the above code to print the lines of a file. The problem is the line only appears for a millisecond. My file only contains a single line of length 70,000 and I want to split it on some substring and then write it to a different file with multiple lines as an output. I also tried saving the read string to an array list inside the while loop.

ArrayList  ArrayList lis = new ArrayList()
lis.add(l)

Also,

lis.size()

It shows that the string is successfully copied to the array list.

lis.get(0).length()

It shows the length of the string inside the list. But some how I can't read the string neither in the code below nor in SysOut.

System.out.println(lis.get(0))

I am not sure what I am doing wrong. Also I tried the above code with some other text file with multiple lines, it works. Ignore the errors in the code above(if any), I typed it here. Thanks!

What I have tried:

public static void main(String args[]) {
    String l = null;
    try{
        File file = new File("sample.txt");
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        int i = 0;
        while((l = br.readLine()) != null){
            System.out.println(l);
        }
        br.close();
    }
    catch(FileNotFoundException e){
        System.out.println("File Not Found");
    }
    catch(IOException ex){

    }
}

解决方案

while((l = br.readLine()) != null){


The first time this is called it reads that line into variable l, which you then display. The next time it is called, the end of file is reached, so readLine returns null, and the program terminates.

You need to do some more processing each time you receive a non-null line of text.


这篇关于从文件中读取后无法保留该行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆