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

お気に入りのデバッグツールを使用して、コードを1つずつステップ実行します。私が考えていることの1つは、メソッドを2回呼び出していることです(これが、デバッガーを使用すると役立つ場合があります。問題の切り分けにも役立ちます)。これは、jList値が変更されたイベントなどのswingイベントの結果としてメソッドが呼び出された場合に発生する可能性があります(これらは常に私を取得します)。幸運を!

特定の理由でそのメソッドを使用する必要があるかどうかはわかりませんが、 Javaヘルパーライブラリからこのメソッドを試すこともできます。

  /**
   * 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 に答える