3

私の質問:システム標準の行セパレーターとして行セパレーターを処理するように入力ストリームを強制するにはどうすればよいですか?

ファイルを文字列に読み取り、改行はに変換されます\nが、私のSystem.getProperty("line.separator");\r\n. これを移植可能にしたいので、ファイルリーダーに改行をシステム標準の改行文字として読み取らせたい(それが何であれ)。どうすれば強制できますか?ファイルを文字列として読み取るためのJava Helper Libraryのメソッドを次に示します。

/**
* Takes the file and returns it in a string. Uses UTF-8 encoding
*
* @param fileLocation
* @return the file in String form
* @throws IOException when trying to read from the file
*/
public static String fileToString(String fileLocation) throws IOException {
  InputStreamReader streamReader = new InputStreamReader(new FileInputStream(fileLocation), "UTF-8");
  return readerToString(streamReader);
}

/**
* Returns all the lines in the Reader's stream as a String
*
* @param reader
* @return
* @throws IOException when trying to read from the file
*/
public static String readerToString(Reader reader) throws IOException {
  StringWriter stringWriter = new StringWriter();
  char[] buffer = new char[1024];
  int length;
  while ((length = reader.read(buffer)) > 0) {
    stringWriter.write(buffer, 0, length);
  }
  reader.close();
  stringWriter.close();
  return stringWriter.toString();
}
4

4 に答える 4

2

BufferedReaderポータブルな方法でファイルを行ごとに読み取るために使用することをお勧めします。その後、選択した行区切り記号を使用して、読み取った各行を必要な出力に書き込むために使用できます。

于 2012-06-25T16:12:58.017 に答える
2

あなたのメソッドは、行末に対して何もreaderToStringしません。文字データをコピーするだけです。それだけです。問題をどのように診断しているかは完全に不明ですが、そのコードは実際に. ファイルにある必要があります-16進エディターで確認する必要があります。そもそもファイルを作成したのは何ですか? 改行がどのように表現されているかを確認する必要があります。\n\r\n\r\n

行を読みたい場合は、 、またはBufferedReader.readLine()に対応する which を使用します。\r\n\r\n

Guavaには、リーダーからすべてのデータを読み取るだけでなく、リーダーを行に分割するなどの便利な方法がたくさんあることに注意してください。

于 2012-06-25T16:17:01.737 に答える
1

Scanner#useDelimiterメソッドを使用すると、Fileまたはその他から読み取るときに使用する区切り文字を指定できますInputStream

于 2012-06-25T16:14:08.520 に答える
1

BufferedReader を使用して、ファイルを 1 行ずつ読み取り、行区切り記号を変換できます。次に例を示します。

public static String readerToString(Reader reader) throws IOException {
    BufferedReader bufReader = new BufferedReader(reader);
    StringBuffer stringBuf = new StringBuffer();
    String separator = System.getProperty("line.separator");
    String line = null;

    while ((line = bufReader.readLine()) != null) {
      stringBuf.append(line).append(separator);
    }
    bufReader.close();
    return stringBuf.toString();
}
于 2012-06-25T16:27:00.333 に答える