Malloc
Malloc

Reputation: 55

Trying to save a String representation of zip file contents as a file in Java

I have the contents of a zip file that I received from a clients multipart form data api stored as a String.

I simply want to save this data now as a zip file; however, when I try saving to a file as below then when I attempt to open the file I get a message stating

"Windows cannot open the folder. The compressed (zipped) Folder 'C:\payload.zip' is invalid."

public void createFile(String data) {
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter("c:\\payload.zip"));
        out.write(data);   
        out.close();
    }
    catch (IOException e)
    {
        System.out.println("Exception ");

    }
}

I am simply passing the String that I receive to the little test createFile method shown above.

I thought that I would paste the actual String contents below but when I attempt to do so it converts it to this (Without the double quotes): " PK"

Any help with what I am doing wrong?

Upvotes: 0

Views: 2398

Answers (2)

Vanna
Vanna

Reputation: 756

To save the text representation of your zip as a zip file again:

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                                               new FileOutputStream("c:\\dest.zip"),
                                               "Cp1252"));
writer.write(data);   
writer.close();

Or you can try:

FileOutputStream fos = new FileOutputStream("C:\\dest.zip");
fos.write(data.getBytes());
fos.close();

Upvotes: 0

Jeeppp
Jeeppp

Reputation: 1573

You can create a file with .zip extension using BufferedWriter but don't expect that file to be a compression file (which is binary)

You can use something like below

Look at this example:

StringBuilder sb = new StringBuilder();
sb.append("your string data");

File f = new File("c:\\payload.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry("myFile.txt");
out.putNextEntry(e);
byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
out.close();

Upvotes: 1

Related Questions