如何将字节数组转换为所有文件类型的字符串

时间:2017-04-20 09:33:59

标签: java arrays byte tostring

目前我可以从数据库中获取BLOB数据类型的数据。 因此在代码中它将存储在byte []中。 现在我可以通过提到字符集(例如.UTF-8)将字节数组转换为字符串,如下所示:

public byte[] mtdFileEncryption(byte[] myData,String fileName) throws DNSException, Exception
{
    String strLocalFolder = SysProperties.getprocessFile_LOCAL_FOLDER();
    String strOnlineSSTPublicKey = SysProperties.getOnline_SST_ENCRYPTION_PUBLIC_KEY();
    String strFilename = fileName;
    PGPFileEncryptor fileEncryptor = new com.test.PGPFileEncryptor();

    File outputFile = null;
    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    BufferedWriter bufferOutput = null;

    File toFile = new File(strLocalFolder);
    if(!toFile.isDirectory())
    {
    //Create temp folder
    toFile.mkdir();
    }

    try
    {
        //generate file to local folder
        //outputFile = new File(strLocalFolder + strFilename + ".txt");

        outputFile = new File(strLocalFolder + strFilename);
        fos = new FileOutputStream(outputFile);
        osw = new OutputStreamWriter(fos);
        bufferOutput = new BufferedWriter(osw);
        //WORKING FOR TXT
        String str = new String(myData, "UTF-8");
        bufferOutput.write(str);

    }catch(Exception e)
    {
        e.printStackTrace();
        throw e;
    }finally
    {
        if(bufferOutput != null)
        {
            bufferOutput.close();
            bufferOutput = null;
        }

        if (osw != null)
        {
            osw.close();
            osw = null;
        }

        if (fos != null)
        {
            fos.close();
            fos = null;
        }
    }

这意味着以下内容可以转换为字符串,我可以查看.txt存储文件的内容

//WORKING FOR TXT
        String str = new String(myData, "UTF-8");
        bufferOutput.write(str);

但是其他文件,.pdf或.xls不会发生这种情况 我无法查看内容。 我可以知道如何在不指定字符集的情况下将字节数组(myData)转换为所有文件类型(.pdf,.xls等)的字符串吗?

以下是字节数组[]传递给方法的方法。 file_content是表中的BLOB数据类型。

    String contentString = rsStatementRequest.getValue("file_content");
                    BASE64Decoder en = new BASE64Decoder();
                    byte[] contentBytes = en.decodeBuffer(contentString);
contentBytes = mtdFileEncryption(contentBytes,fileName);

1 个答案:

答案 0 :(得分:2)

我建议用二进制编写byte [] BLOB。写作是因为文本可能会破坏它,如果它是加密的话。

public void mtdFileEncryption(byte[] myData,String fileName) throws IOException {
    String strLocalFolder = SysProperties.getprocessFile_LOCAL_FOLDER();
    new File(strLocalFolder).mkdir();

    try (FileOutputStream fos = new FileOutputStream(new File(strLocalFolder, fileName)) {
         fos.write(myData);
    }
}