如果论坛中已经讨论过这个问题,请原谅我,但我一直在寻找问题的答案。
我可能不完全了解上传组件的工作原理。我计划将一个文件保存到我的服务器,稍后可以将该文件的内容读取到表格或文本区域中。
这是我的接收上传文件方法,我正在写入文件并返回文件输出流。
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
outputFile = new File("/tmp/" + filename);
fos = new FileOutputStream(outputFile);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
上传成功后,这是我的代码
public void uploadFinished(Upload.FinishedEvent finishedEvent) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
textArea.setValue(textArea.getValue() + "n" + line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
这一切都有效并输出文件的内容,例如 PDF 或文本文件,但内容都用奇数编码包装,例如
{\rtf1\ansi\ansicpg1252\cocoartf1348\cocoasubrtf170 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\fs24 \cf0 hi there\ \ bye}
原始文件的保存位置
嘿,你好
再见
我正在做什么来包含所有元数据等?
另外我想注意的是,我添加了标准字符集。UTF8 到输入流希望解决这个问题,但它与不包括这个完全相同。
该文件似乎不是文本文件,而是PDF文件。在 uploadDone() 方法中,您可以首先使用 https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path) 测试文件类型。如果文件是PDF,您可以使用PDFBox(如何使用Java读取PDF文件?)来阅读内容,或者如果它是纯文本,则可以按原样阅读。
import java.nio.file.Files;
import java.nio.file.Path;
...
String contentType = Files.probeContentType(outputFile.toPath());
if(contentType.equals("application/pdf"))
{
PDDocument document = null;
document = PDDocument.load(outputFile);
document.getClass();
if( !document.isEncrypted() ){
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition( true );
PDFTextStripper Tstripper = new PDFTextStripper();
String st = Tstripper.getText(document);
textArea.setValue(st);
}
}catch(Exception e){
e.printStackTrace();
}
}
else if(contentType.equals("text/plain"))
{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
textArea.setValue(textArea.getValue() + "n" + line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}