我是一个新手,正在尝试弄清楚如何使用uuencode方法。我们有一个只允许上传单个文本文件的表单。现在看起来只有zip文件会被上传。我正在尝试包含uuencode方法来将字节转换为字符串,这样我们就不必修改代码的其余部分来适应二进制文件。
原始代码:
public void SettingUpload(File inputfile) {
this.inputfile = inputfile;
}我把它改成
public void SettingUpload(File inputfile){
UUEncoder uuec = new UUEncoder();
try{
InputStream is = new FileInputStream(inputfile);
OutputStream os = new FileOutputStream(inputfile);
uuec.encodeBuffer(is, os);
this.inputfile = inputfile;
}catch (Throwable error) {
reportError(error, "Error converting zipfile");
}
}当我测试它的时候,我得到了一个java.io.EOFException。我抓取了uuencoded文件,并手动对其进行了uudecoded编码。当我试图解开它的时候,
bash1:~>unzip s6b0c9e663c74f72941bd8271a5fac3b.bin
Archive: s6b0c9e663c74f72941bd8271a5fac3b.bin
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the编辑:
我将其更改为:
public void SettingUpload(File inputfile){
UUEncoder uuec = new UUEncoder();
try{
InputStream is = new FileInputStream(inputfile);
File OutputFile=new File("Output");
OutputFile.createNewFile();
OutputStream os = new FileOutputStream(OutputFile);
uuec.encodeBuffer(is, os);
this.OutputFile = OutputFile;
}catch (Throwable error) {
reportError(error, "Error converting zipfile");
}
}我得到了以下错误:
cannot find symbol
symbol : variable OutputFile发布于 2012-10-04 14:32:31
正如浩准所评论的,你不应该这样做:
InputStream is = new FileInputStream(inputfile); // Good
OutputStream os = new FileOutputStream(inputfile); // Bad你应该输出到一个单独的文件,否则在你第一次写的时候,你会丢弃原始的文件。
使用示例更新了
这对我来说很好。
public static void main(String[] args) {
File inputfile = new File("file/to/be/encoded");
File outFile = new File("out.uue");
UUEncoder uuec = new UUEncoder();
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(inputfile);
os = new FileOutputStream(outFile);
uuec.encodeBuffer(is, os);
} catch (Exception error) {
error.printStackTrace();
} finally {
try {
is.close();
} catch (Exception e) {
}
try {
os.close();
} catch (Exception e) {
}
}
File newFile = new File("decoded.jpg");
UUDecoder decoder = new UUDecoder();
try {
is = new FileInputStream(outFile);
os = new FileOutputStream(newFile);
decoder.decodeBuffer(is, os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (Exception e) {
}
try {
os.close();
} catch (Exception e) {
}
}
}此外,我还将返回encode方法的输出文件
public void SettingUpload(File inputfile) throws IOException {
UUEncoder uuec = new UUEncoder();
File outFile = File.createTempFile("encoded", "uue");
InputStream is = null;
OutputStream os = null;
try{
is = new FileInputStream(inputfile);
os = new FileOutputStream(outFile );
uuec.encodeBuffer(is, os);
} finally {
try {
is.close();
} catch (Exception e) {
}
try {
os.close();
} catch (Exception e) {
}
}
return outFile;
}您永远不应该抑制异常。调用者如何知道是否出了问题?
另外,如果你打开一个流,你要负责关闭它,所以一定要关闭你的流。
https://stackoverflow.com/questions/12721472
复制相似问题