簡體   English   中英

JAVA:使用InputStreamReader打開和讀取文件

[英]JAVA: Open and read file using InputStreamReader

我正在嘗試使用InputStreamReader讀取二進制文件(pdf,doc,zip)。 我使用FileInputStream實現了這一目的,並將文件的內容保存到字節數組中。 但是我被要求使用InputStreamReader做到這一點。 因此,當我嘗試打開並閱讀pdf文件時,例如使用

File file = new File (inputFileName); 
Reader in = new
InputStreamReader(new FileInputStream(file)); 
char fileContent[] = new char[(int)file.length()]; 
in.read(fileContent); in.close();

然后使用將該內容保存到另一個pdf文件

File outfile = new File(outputFile);
Writer out = new OutputStreamWriter(new FileOutputStream(outfile));
out.write(fileContent);
out.close();

一切正常(沒有異常或錯誤),但是當我嘗試打開新文件時,它表示文件已損壞或編碼錯誤。

有什么建議嗎?

ps1我特別需要使用InputStreamReader

ps2嘗試讀取/寫入.txt文件時工作正常

String, char, Reader, Writer適用於Java中的文本 該文本是Unicode,因此可以合並所有腳本。

byte[], InputStream, OutputStream用於二進制數據。 如果它們表示文本,則必須將它們與某種編碼關聯。

文本和二進制數據之間的橋梁總是涉及轉換。

在您的情況下:

Reader in = new InputStreamReader(new FileInputStream(file), encoding);
Reader in = new InputStreamReader(new FileInputStream(file)); // Platform's encoding

第二個版本是不可移植的,因為其他計算機可以具有任何編碼。

在您的情況下,請勿對二進制數據使用InputStreamReader。 轉換只能破壞事物。

也許它們的意思是:不要讀取字節數組中的所有內容。 在這種情況下,請使用BufferedInputStream重復讀取小字節數組(緩沖區)。

不要使用讀取器/寫入器API。 改用二進制流:

File inFile = new File("...");
File outFile = new File("...");
FileChannel in = new FileInputStream(inFile).getChannel();
FileChannel out = new FileOutputStream(outFile).getChannel();

in.transferTo(0, inFile.length(), out);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM