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

时间:2012-04-22 17:29:02

标签: java file file-io

我正在使用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 !

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

1 个答案:

答案 0 :(得分:0)

使用您最喜欢的调试工具,逐步执行代码。我正在考虑的一件事是你正在调用该方法两次(这就是为什么使用调试器可能有所帮助。它也可以帮助你隔离问题)。如果你的方法被调用作为jList值更改事件之类的swing事件或类似的东西(那些总是得到我),就会发生这种情况。祝你好运!

我不确定您是否需要将此方法用于任何特定原因,但您也可以尝试this method中的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();
  }