请原谅我,如果在论坛中讨论过这个问题,但我一直在寻找问题的答案。
我可能不完全了解上传组件的工作原理。我计划将文件保存到我的服务器,以后我可以将其内容读入表格或文本区域。
这是我的接收上传文件方法,我写入文件并返回FileOutputStream。
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你好\ \ bye}
原始文件的保存位置
你好
再见
我在做什么来包含所有元数据等?
另外我想注意我将standardcharset.UTF8添加到输入流中以希望解决此问题,但它与完全相同,不包括此内容。
答案 0 :(得分:0)
该文件似乎不是文本文件,而是PDF文件。在uploadFinished()方法中,您可以先使用https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path)测试文件类型。如果文件是PDF,您可以使用PDFBox(How to read PDF files using Java?)来阅读内容,或者如果是纯文本,您可以按原样阅读。
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();
}
}