BufferedReader
少しテストした後、さまざまな状況で問題があることがわかりScanner
ました(前者は新しい行を検出できないことが多く、後者はorg.jsonライブラリによってエクスポートされたJSON文字列などからスペースを削除することがよくあります)。利用可能な他の方法もありますが、問題は、特定のJavaバージョン(たとえば、Android開発者にとっては悪い)の後でのみサポートされ、このような単一の目的のためだけにGuavaまたはApacheコモンズライブラリを使用したくない場合があります。したがって、私の解決策は、ファイル全体をバイトとして読み取り、それを文字列に変換することです。以下のコードは、私の趣味のプロジェクトの1つから取られています。
/**
* Get byte array from an InputStream most efficiently.
* Taken from sun.misc.IOUtils
* @param is InputStream
* @param length Length of the buffer, -1 to read the whole stream
* @param readAll Whether to read the whole stream
* @return Desired byte array
* @throws IOException If maximum capacity exceeded.
*/
public static byte[] readFully(InputStream is, int length, boolean readAll)
throws IOException {
byte[] output = {};
if (length == -1) length = Integer.MAX_VALUE;
int pos = 0;
while (pos < length) {
int bytesToRead;
if (pos >= output.length) {
bytesToRead = Math.min(length - pos, output.length + 1024);
if (output.length < pos + bytesToRead) {
output = Arrays.copyOf(output, pos + bytesToRead);
}
} else {
bytesToRead = output.length - pos;
}
int cc = is.read(output, pos, bytesToRead);
if (cc < 0) {
if (readAll && length != Integer.MAX_VALUE) {
throw new EOFException("Detect premature EOF");
} else {
if (output.length != pos) {
output = Arrays.copyOf(output, pos);
}
break;
}
}
pos += cc;
}
return output;
}
/**
* Read the full content of a file.
* @param file The file to be read
* @param emptyValue Empty value if no content has found
* @return File content as string
*/
@NonNull
public static String getFileContent(@NonNull File file, @NonNull String emptyValue) {
if (file.isDirectory()) return emptyValue;
try {
return new String(readFully(new FileInputStream(file), -1, true), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
return emptyValue;
}
}
getFileContent(file, "")
単にファイルの内容を読み取るために使用できます。