How do I save a String to a text file using Java?

后端 未结 24 1518
不知归路
不知归路 2020-11-22 04:18

In Java, I have text from a text field in a String variable called \"text\".

How can I save the contents of the \"text\" variable to a file?

24条回答
  •  梦谈多话
    2020-11-22 04:31

    My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.

    As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.

    public boolean writeStringToFile(File file, String string, Charset charset) {
        if (file == null) return false;
        if (string == null) return false;
        return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
    }
    
    public boolean writeBytesToFile(File file, byte[] data) {
        if (file == null) return false;
        if (data == null) return false;
        FileOutputStream fos;
        BufferedOutputStream bos;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(data, 0, data.length);
            bos.flush();
            bos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Logger.e("!!! IOException");
            return false;
        }
        return true;
    }
    

提交回复
热议问题