gpt4 book ai didi

java - 使用 FileItemStream 在 Java 中处理二进制文件

转载 作者:行者123 更新时间:2023-11-29 03:49:43 24 4
gpt4 key购买 nike

我有一个允许上传二进制文件的网络应用程序。我必须解析它们并将内容 1:1 保存到一个字符串中,然后再保存到数据库中。

当我在 unix 机器上使用 uuencode 对二进制文件进行编码时,它就可以工作了。有没有办法在 Java 中自动执行此操作?

if (isMultipart) {

//Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();

//Parse the request
FileItemIterator iter = upload.getItemIterator(request);

while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();

InputStream stream = item.openStream();

if (!item.isFormField()) {

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
licenseString = "";

while ((line = reader.readLine()) != null) {
System.out.println(line);

// Generate License File
licenseString += line + "\n";
}
}
}
session.setAttribute("licenseFile", licenseString);
System.out.println("adding licensestring to session. ");
}

它当然适用于所有上传的非二进制文件。我如何扩展它以支持二进制文件?

最佳答案

// save to file
// =======================================
InputStream is = new BufferedInputStream(item.openStream());
BufferedOutputStream output = null;

try {
output = new BufferedOutputStream(new FileOutputStream("temp.txt", false));
int data = -1;
while ((data = is.read()) != -1) {
output.write(data);
}
} finally {
is.close();
output.close();
}

// read content of file
// =======================================
System.out.println("content of file:");
try {
FileInputStream fstream = new FileInputStream("temp.txt");

DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;

licenseString = "";
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()));
licenseString += javax.xml.bind.DatatypeConverter.printBase64Binary(strLine.getBytes()) + "\n";
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}

关于java - 使用 FileItemStream 在 Java 中处理二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9375697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com