开发者

Java Applet - Convert File to String

开发者 https://www.devze.com 2022-12-19 03:35 出处:网络
How can conve开发者_高级运维rt a certain file into in a String? And then from that String to get the original file? This needs to realize it using Java.

How can conve开发者_高级运维rt a certain file into in a String? And then from that String to get the original file? This needs to realize it using Java.

It would be greate an example of code or a link to a tutorial.

Have to converted an entire File (not thecontent) in the String and then the String to the File.

Thanks.


NB: In both cases below you will have to digitally sign your applet, so that it is granted permissions to read/write from/to the file system!

If you can use external libraries, use Apache commons-io (you will have to sign these jars as well)

FileUtils.readFileToString(..)

FileUtils.writeStringToFile(..)

If you can't, you can see this tutorial.

This is for text files - but if you want to read binary files (.png for instance), you should not read it as string. Instead read it as byte[] and use commons-codec -

encode: String base64String = new String(Base64.encodeBase64(byteArray));

decode: byte[] originalBytes = Base64.decodeBase64(string.getByte());

Base64 is a string format for storing binary data.


public static String getFileContent(File file) throws IOException
{
FileReader in=new FileReader(file);
StringWriter w= new StringWriter();
char buffer[]=new char[2048];
int n=0;
while((n=in.read(buffer))!=-1)
 {
 w.write(buffer, 0, n);
 }
w.flush();
in.close();
return w.toString();
}

public static void toFileContent(String s,File file) throws IOException
{
FileWriter f=new FileWriter(file);
f.write(s);
f.flush();
f.close();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消