0

我正在使用 Java 从文件中读取文本。这是我的代码:

public void readCurrentPage(){
    FileInputStream file = null;
    BufferedInputStream buff = null;
    int readByteValue;
    Exception lastShownException = null;
    boolean errorShown = false;
    boolean readOnce;

    try{
        errorShown = false;
        file = new FileInputStream("/Volumes/Storage Drive/eclipse/workspace/Nicholas Planner/bin/data/test.txt");
        buff = new BufferedInputStream(file,8*1024);
        while (true){
            readByteValue = buff.read();
            if (readByteValue == -1){
                break;
            }
            System.out.print((char) readByteValue + " ");

        }

    }catch(Exception e){
        if(errorShown == false && lastShownException!=e){
            JOptionPane.showMessageDialog(null, "There was an error: \n"+e, "Error!", 1);
            e = lastShownException;
            errorShown = true;
        }

    }finally{
        try{
            errorShown = false;
            buff.close();
            file.close();
        }catch(Exception e){
            if(errorShown == false && lastShownException!=e){
                JOptionPane.showMessageDialog(null, "There was an error: \n"+e, "Error!", 1);
                e = lastShownException;
                errorShown = true;
            }
        }
    }
}

这是文件的文本:

test
This is cool!

当我使用上面的代码读取文件时,我得到的是:

t e s t 
 T h i s   i s   c o o l ! t e s t 
 T h i s   i s   c o o l !

为什么我的代码会重复文件的文本?

4

1 回答 1

0

使用您最喜欢的调试工具,一次单步执行一个代码。我认为可能的一件事是您两次调用该方法(这就是为什么使用调试器会有所帮助。它还可以帮助您隔离问题)。如果您的方法由于诸如 jList 值更改事件之类的摇摆事件或类似事件(这些总是让我明白)而被调用,则可能会发生这种情况。祝你好运!

我不确定您是否出于任何特殊原因需要使用该方法,但您也可以尝试Java Helper Library中的此方法

  /**
   * Takes the file and returns it in a string
   *
   * @param location
   * @return
   * @throws IOException
   */
  public static String fileToString(String location) throws IOException {
    FileReader fr = new FileReader(new File(location));
    return readerToString(fr);
  }

  /**
   * Takes the given resource (based on the given class) and returns that as a string.
   *
   * @param location
   * @param c
   * @return
   * @throws IOException
   */
  public static String resourceToString(String location, Class c) throws IOException {
    InputStream is = c.getResourceAsStream(location);
    InputStreamReader r = new InputStreamReader(is);
    return readerToString(r);
  }

  /**
   * Returns all the lines in the scanner's stream as a String
   *
   * @param r
   * @return
   * @throws IOException
   */
  public static String readerToString(InputStreamReader r) throws IOException {
    StringWriter sw = new StringWriter();
    char[] buf = new char[1024];
    int len;
    while ((len = r.read(buf)) > 0) {
      sw.write(buf, 0, len);
    }
    r.close();
    sw.close();
    return sw.toString();
  }
于 2012-04-22T19:45:50.590 回答