如何在FileWriter中使用java / jsp将编码的文本写入文件?

FileWriter testfilewriter = new FileWriter(testfile, true);
testfilewriter.write(testtext);

testtext:- is text
testfile:- is String (Encoded)


我想做的是用Base64编码测试文件并将其存储在文件中。最好的方法是什么?

最佳答案

由于您的数据不是纯文本,因此无法使用FileWriter。您需要的是FileOutputStream

将您的文本编码为Base64:

byte[] encodedText = Base64.encodeBase64( testtext.getBytes("UTF-8") );


并写入文件:

try (OutputStream stream = new FileOutputStream(testfile)) {
    stream.write(encodedText);
}


或者,如果您不想丢失现有数据,请通过将append布尔值设置为true来以追加模式进行写入:

try (OutputStream stream = new FileOutputStream(testfile, true)) {
    stream.write(encodedText);
}

关于java - 如何使用Java将编码的文本写入文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29938817/

10-10 09:48