Generate file by reading a database field

Asked

Viewed 39 times

0

I’m having trouble generating files (both text and binary). The text files are not coming out with the correct encoding, and the binaries are corrupted. I’m using java 5 and struts.

The code to generate the files is

        final byte[] array = (byte[]) hashMap.get("BINARY_FILE");
    if (array != null && array.length > 0) {
        bis = new BufferedInputStream(new ByteArrayInputStream(array));
    }

    file = new File(tempDir.getAbsolutePath() + "\\" + path + fileName);
    final FileOutputStream fos = new FileOutputStream(file);

    if (!file.exists()) {
        file.createNewFile();
    }

    baos = new ByteArrayOutputStream();

    int c;
    if (size >= SIZE_LIMIT) {
        final BufferedOutputStream bos = new BufferedOutputStream(fos);
        for (int i = 0; i < size; i++) {
        bos.write(i);
        }
        bos.flush();
        bos.close();
    } else {
        while ((c = bis.read()) != -1) {
        fos.write(array);
        }
    }

    fos.flush();
    fos.close();

1 answer

0

A cool idea is to save your object serializado.

public static void saveObject(Object object, String caminho, String nameOfArchive) throws FileNotFoundException, IOException
{
    FileOutputStream fileOutputStream = new FileOutputStream(caminho.concat(File.separator).concat(nameOfArchive));
    ObjectOutputStream of = new ObjectOutputStream(fileOutputStream);

    of.writeObject(object);

    of.close();
    fileOutputStream.close();
}

That way, if you’re going to reuse it on your system, you can do the following:

public static Object getObject(String arquivo) throws FileNotFoundException, IOException, ClassNotFoundException
{
    FileInputStream fi = new FileInputStream(arquivo);
    ObjectInputStream objInput = new ObjectInputStream(fi);
    Object _retorno = (Object) objInput.readObject();
    objInput.close();

    return _retorno;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.