在java中读取文本文件直到EOF

时间:2013-10-02 17:29:12

标签: java

我正在尝试阅读一个包含 -

的文本文件
  

你好詹姆斯!

     

今天你好!

我使用以下代码:

int readedValue;

do
{   
    while((readedValue = bufferReader.read()) != 10)
   {
    //readedValue = bufferReader.read();
    char ch = (char) readedValue;
    System.out.print(ch);
   } 

}
while ((readedValue = bufferReader.read()) != -1);

当我现在读到这个文件的时候,我得到的输出是你好詹姆斯!今天你好!

我没有得到'怎么样。如何更改此内容以获取完整文本?

4 个答案:

答案 0 :(得分:1)

我认为你需要这个...

int readedValue;

while ((readedValue = bufferReader.read()) != -1)
{   
    if(readedValue  != 10)
    {
         System.out.print((char) readedValue);
   } 

}

答案 1 :(得分:1)

你在do-while循环条件

中丢失了一个角色
do {
    ...
    // ends when the first new line \n character is reached
}
while ((readedValue = bufferReader.read()) != -1);
        ^ never printed 
// the character that isn't read is the first character after the \n, ie. 'H'

使用存储readedValue(readValue)的单个循环并对其进行任何比较。

答案 2 :(得分:0)

在您的示例中,当遇到换行符时,您正在读取字符两次ascii 10

do
{   
    while((readedValue = bufferReader.read()) != 10) // Here 
   {
    //readedValue = bufferReader.read();
    char ch = (char) readedValue;
    System.out.print(ch);
   } 

}
while ((readedValue = bufferReader.read()) != -1); // Again here

你应该做的只是阅读一次

while ((readedValue = bufferReader.read()) != -1)
{   
    if(readedValue != 10) 
   {
    char ch = (char) readedValue;
    System.out.print(ch);
   } 

}

答案 3 :(得分:0)

这会对你有所帮助:

String line;
int readedValue;
String s = "hello James!\n\rHow are you today!";
StringReader input = new StringReader(s);
BufferedReader lineReader= new BufferedReader (input);

while((line=lineReader.readLine())!=null) {
    StringReader input2 = new StringReader(line);
    BufferedReader charReader= new BufferedReader (input2);
    while((readedValue = charReader.read()) != -1) {
        char ch = (char) readedValue;
        System.out.print(ch);
    }
}