简体   繁体   中英

How to write encoded text to a file using Java?

How to write encoded text to a file using java/jsp with FileWriter?

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

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

What I m trying to do is encoding testfile with Base64 and storing it in file. What is the best way to do so?

Since your data is not plain text, you can't use FileWriter. What you need is FileOutputStream .

Encode your text as Base64:

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

and write to file:

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

or if you don't want to lose existing data, write in append mode by setting append boolean to true:

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

You can do the encoding yourself and then write to the file as suggested by @Alper OR if you want to create a stream which does encoding/decoding to while writing and reading from file , apache commons codec library will come in handy see Base64OutputStream and Base64InputStream

Interestingly Java 8 has a similar API Base64.Encoder . Checkout the wrap method

Hope this helps.

The Approach to be followed depends on the algorithm you are using and writing the encoded file is same as writing the file in java

IMHO, if you are trying to do it using jsp , Kindly go with servlets .As jsp are not meant for business layers rather do servlets.

I'm not going to give the code, as it is pretty easy if you try it. I'll share the best way to do it as a psuedo code. Here are steps to write your encoded text.

  1. Open input file in read mode & output file in append mode.
  2. If input file isn't huge (it can fit in memory) then read whole file at once, otherwise read line-by-line.
  3. Encode the text retrieved from file using Base64Encoder
  4. Write in the output file in append mode.

You can't use a FileWriter directly for this task.

You asked how you can do it, but you didn't give any information about which JDK and library you use, so here are a few solutions with the standard tools.

If you're using Java 8 :

String testFile = "";
try (Writer writer = new OutputStreamWriter(
    Base64.getEncoder().wrap(
        java.nio.file.Files.newOutputStream(
            Paths.get(testFile),
            StandardOpenOption.APPEND)),
    StandardCharsets.UTF_8)
    ) {
  writer.write("text to be encoded in Base64");
}

If you're using Java 7 with Guava :

String testFile = "";
CharSink sink = BaseEncoding.base64()
    .encodingSink(
        com.google.common.io.Files.asCharSink(
            new File(testFile),
            StandardCharsets.UTF_8,
            FileWriteMode.APPEND))
    .asCharSink(StandardCharsets.UTF_8);
try (Writer writer = sink.openStream()) {
  writer.write("text to be encoded in Base64");
}

If you're using Java 6 with Guava :

String testFile = "";
CharSink sink = BaseEncoding.base64()
    .encodingSink(
        com.google.common.io.Files.asCharSink(
            new File(testFile),
            Charsets.UTF_8,
            FileWriteMode.APPEND))
    .asCharSink(Charsets.UTF_8);
Closer closer = Closer.create();
try {
  Writer writer = closer.register(sink.openStream());
  writer.write("text to be encoded in Base64");
} catch (Throwable e) { // must catch Throwable
  throw closer.rethrow(e);
} finally {
  closer.close();
}

I don't have much knowledge about other libraries so I won't pretend I do and add another helper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM