Best way to write String to file using java nio

后端 未结 5 1918
清歌不尽
清歌不尽 2021-01-30 12:49

I need to write(append) huge string to flat file using java nio. The encoding is ISO-8859-1.

Currently we are writing as shown below. Is there any better

5条回答
  •  北海茫月
    2021-01-30 13:42

    Here is a short and easy way. It creates a file and writes the data relative to your code project:

    private void writeToFile(String filename, String data) {
        Path p = Paths.get(".", filename);
        try (OutputStream os = new BufferedOutputStream(
            Files.newOutputStream(p, StandardOpenOption.CREATE, StandardOpenOption.APPEND))) {
            os.write(data.getBytes(), 0, data.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题