2014-04-23 88 views
0
public void file(){ 
     String fileName = "hello.txt"; 
     fileName = FileBrowser.chooseFile(true); 


     //Open a file and store the information into the OurList 
     try 
     { 
      String s = ""; 
      File file = new File(fileName); 
      FileReader inputFile = new FileReader(file); 
      while(inputFile.read() != -1) 
      { 
       System.out.println(inputFile.read()); 
       System.out.println(); 
      } 
     } 
     catch(Exception exception) 
     { 
      System.out.println("Not a real file. List is already built"); 
     } 

    } 

所以我有这段代码的麻烦。我想从文件中逐字逐字地阅读,但现在它正在跳过其他文件。我知道它为什么会跳过,它在while循环中以及何时尝试打印,但据我所知,没有其他方法可以停止FileReader,然后将其设置为!= -1。我怎样才能让它不跳过?跳过我的文件读取器

回答

1

你在循环中调用read()两次,所以你没有看到每个奇怪的字符。您需要将read()的结果存储在一个变量中,对它进行测试,如果是,则中断,否则打印该变量。

+0

感谢。我知道这是跳过,因为我有两个电话,但无法弄清楚如何将它存储到一个变量之前。生病的时候改变它做。再次感谢。 – user2743857

+0

@ user2743857:请将EJP的答案标记为已接受。 –

0

使用此模式:

 int value = inputFile.read(); 
     while(value != -1) 
     { 
      System.out.println(value); 
      System.out.println(); 
      value = inputFile.Read(); 
     } 
1
int nextChar; 
while((nextChar = inputFile.read()) != -1) 
    { 
     System.out.println(nextChar); 
     System.out.println(); 
    } 
0

正如你已经知道,你是调用read(),每个循环两次,这导致的问题。

下面是一些常见的方法正确环路和阅读:

一个松散,但是工作的方式,我相信大多数人可以自己弄清楚的是:

boolean continueToRead = true; 
while(continueToRead) { 
    int nextChar = file.read(); 
    if (nextChar != -1) { 
     .... 
    } else { // nextChar == -1 
     continueToRead = false; 
    } 
} 

或使用破:

while(true) { 
    int nextChar = file.read(); 
    if (nextChar == -1) { 
     break; 
    } 

    .... 
} 

的清洁器模式:

int nextChar = file.read(); 
while (nextChar != -1) { 
    .... 
    nextChar = file.read(); 
} 

while ((nextChar = file.read()) != -1) { 
    .... 
} 

我更成使用循环:

for (int nextChar = file.read(); nextChar != 1; nextChar = file.read()) { 
    .... 
} 
相关问题