42

txtファイルのコンテンツを取得するには、通常、スキャナーを使用し、各行を繰り返してコンテンツを取得します。

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();                     
}

Java APIは、次のような1行のコードでコンテンツを取得する方法を提供しますか?

String content = FileUtils.readFileToString(new File("file.txt"))
4

6 に答える 6

33

組み込みのAPIではありませんが、Guavaは他の宝物の中でも特にそうです。(それは素晴らしいライブラリです。)

String content = Files.toString(new File("file.txt"), Charsets.UTF_8);

Readableを読み取ったり、バイナリファイルの内容全体をバイト配列としてロードしたり、ファイルを文字列のリストに読み込んだりするための同様の方法があります。

このメソッドは非推奨になっていることに注意してください。新しい同等物は次のとおりです。

String content = Files.asCharSource(new File("file.txt"), Charsets.UTF_8).read();
于 2011-04-12T20:17:53.487 に答える
25

Java 7では、これらの方針に沿ってAPIがあります。

Files.readAllLines(パスパス、文字セットcs)

于 2011-04-12T20:18:35.083 に答える
20

commons-ioには次のものがあります。

IOUtils.toString(new FileReader("file.txt"), "utf-8");
于 2011-04-12T20:21:17.480 に答える
11
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public static void main(String[] args) throws IOException {
    String content = Files.readString(Paths.get("foo"));
}

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)から

于 2016-05-26T16:06:47.220 に答える
7

FileReaderクラスをBufferedReaderと一緒に使用して、テキストファイルを読み取ることができます。

File fileToRead = new File("file.txt");

try( FileReader fileStream = new FileReader( fileToRead ); 
    BufferedReader bufferedReader = new BufferedReader( fileStream ) ) {

    String line = null;

    while( (line = bufferedReader.readLine()) != null ) {
        //do something with line
    }

    } catch ( FileNotFoundException ex ) {
        //exception Handling
    } catch ( IOException ex ) {
        //exception Handling
}
于 2016-10-27T12:04:30.893 に答える
0

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, "")単にファイルの内容を読み取るために使用できます。

于 2020-08-07T07:41:56.527 に答える