2012-06-27 34 views
18

我有一個可以像ZIP任何東西文件,RAR,TXT,CSV,DOC等。我想從它創建一個ByteArrayInputStream的
我用它來上傳文件通過從阿帕奇百科全書網FTP FTPClient如何從Java中的文件創建ByteArrayInputStream?

是否有人知道該怎麼辦呢?

例如:

String data = "hdfhdfhdfhd"; 
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes()); 

我的代碼:

public static ByteArrayInputStream retrieveByteArrayInputStream(File file) { 
    ByteArrayInputStream in; 

    return in;  
} 
+0

對於文件讀出在我使用的RandomAccessFile和整個文件的字節首先轉移到一個字節數組字節。我發現這是以字節讀取文件的非常快速的方式。 –

+3

你爲什麼需要這樣做?您可以通過將FileInputStream複製到ByteArrayOutputStream,然後從中創建ByteArrayInputStream來完成此操作。它當然沒有意義。 –

+0

請解釋你的用例。你可能只是想要一個FileInputStream。一旦擁有它,你打算如何使用它? –

回答

28

使用FileUtils#readFileToByteArray(File)Apache Commons IO,然後使用ByteArrayInputStream(byte[])構造函數創建ByteArrayInputStream

public static ByteArrayInputStream reteriveByteArrayInputStream(File file) { 
    return new ByteArrayInputStream(FileUtils.readFileToByteArray(file)); 
} 
+16

正如我的回答指出的那樣,Java 7已經在Files類中包含了一個readFileToByteArray,不需要額外的庫。 –

+6

其實,在Java 7中,它是'Files.readAllBytes' –

13

總的想法是,文件會產生一個FileInputStreambyte[]一個ByteArrayInputStream。都實現InputStream所以他們應該與使用InputStream作爲參數的方法兼容。

把所有的文件內容在ByteArrayInputStream可以做,當然:

  1. 讀的完整文件到一個byte[]; Java版本> = 7包含一個convenience method called readAllBytes以讀取文件中的所有數據;
  2. 圍繞創建該文件的內容,這是現在在內存中的ByteArrayInputStream

請注意,這可能不是針對超大文件的最佳解決方案 - 所有文件都將在相同的時間點存儲在內存中。使用正確的工作流是非常重要的。

3

這不完全是你問的,而是一種以字節讀取文件的快速方法。

File file = new File(yourFileName); 
RandomAccessFile ra = new RandomAccessFile(yourFileName, "rw"): 
byte[] b = new byte[(int)file.length()]; 
try { 
    ra.read(b); 
} catch(Exception e) { 
    e.printStackTrace(); 
} 

//Then iterate through b 
+0

如果可以,請填寫你的代碼嗎? – itro

4

A ByteArrayInputStreamInputStream圍繞字節數組的封裝。這意味着您必須將文件完全讀入byte[],然後使用其中一個ByteArrayInputStream構造函數。

你可以提供有關ByteArrayInputStream的詳細信息嗎?它可能有更好的辦法圍繞你想要達到的目標。

編輯:
如果您使用的是Apache FTPClient上傳,你只需要一個InputStream。你可以這樣做;

String remote = "whatever"; 
InputStream is = new FileInputStream(new File("your file")); 
ftpClient.storeFile(remote, is); 

您當然應該記得在完成輸入流後關閉它。

+0

我使用它通過FTPClient commons Apache將文件上傳到ftp。 – itro

+0

@itro - 使用FTPClient詳細信息更新了我的答案 – Qwerky

1

這段代碼來得心應手:

private static byte[] readContentIntoByteArray(File file) 
{ 
    FileInputStream fileInputStream = null; 
    byte[] bFile = new byte[(int) file.length()]; 
    try 
    { 
    //convert file into array of bytes 
    fileInputStream = new FileInputStream(file); 
    fileInputStream.read(bFile); 
    fileInputStream.close(); 
    } 
    catch (Exception e) 
    { 
    e.printStackTrace(); 
    } 
    return bFile; 
} 

參考:http://howtodoinjava.com/2014/11/04/how-to-read-file-content-into-byte-array-in-java/

相關問題