Java Path File Read nio readAsString(Path path)

Here you can find the source of readAsString(Path path)

Description

read As String

License

Apache License

Declaration

public static String readAsString(Path path) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    private static final int IO_BUFFER_SIZE = 8 * 1024;

    public static String readAsString(Path path) throws IOException {
        InputStream in = null;/*w ww  .  j a  v  a 2 s  .co m*/
        try {
            in = Files.newInputStream(path);
            return new String(read(in));
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static byte[] read(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        copy(in, out);
        out.close();

        return out.toByteArray();
    }

    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }

    public static void write(Path path, String string) throws IOException {
        PrintWriter out = null;
        try {
            out = new PrintWriter(Files.newOutputStream(path));
            out.write(string);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

Related

  1. read(String path)
  2. readAllLines(Path path)
  3. readAllLines(String path)
  4. readAllLinesOrExit(Path path)
  5. readAndConsume(String filePath, Consumer consumer)
  6. readAsString(String path)
  7. reader(String path)
  8. readers(String path)
  9. readFile(Path directory, String... parts)