views:

347

answers:

2

How can convert 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.

+1  A: 

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.

Bozho
+1 for mentioning that the applet must be signed to access the filesystem
stacker
A: 
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();
}
Pierre
Does your example work for a .rar, .jpg, ... file?
Emanuel