2012-08-31 113 views
3

我想測試我寫入OutputStream(文件OuputStream)的字節與我從相同的InputStream中讀取的字節相同。如何從InputStream中讀取字節?

測試看起來像

@Test 
    public void testStreamBytes() throws PersistenceException, IOException, ClassNotFoundException { 
     String uniqueId = "TestString"; 
     final OutputStream outStream = fileService.getOutputStream(uniqueId); 
     new ObjectOutputStream(outStream).write(uniqueId.getBytes()); 
     final InputStream inStream = fileService.getInputStream(uniqueId); 
    } 

我意識到InputStream沒有getBytes()

如何測試像

assertEquals(inStream.getBytes(), uniqueId.getBytes()) 

謝謝

回答

1

試試這個(IOUtils是公共-IO)

byte[] bytes = IOUtils.toByteArray(instream); 
+2

我相信IOUtils是commons-io,是不是'Java'提供了類似的東西? – daydreamer

+0

@daydreamer是的,使用'ByteArrayOutputStream'。 – oldrinb

0

Java不提供你想要什麼,但你可以使用類似於PrintWriterScanner的文件包裝流:

new PrintWriter(outStream).print(uniqueId); 
String readId = new Scanner(inStream).next(); 
assertEquals(uniqueId, readId); 
0

您可以從inputstream中讀取數據並寫入ByteArrayOutputStream,然後使用toByteArray()方法將其轉換爲字節數組。

1

你可以使用ByteArrayOutputStream

ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 

int nRead; 
byte[] data = new byte[16384]; 

while ((nRead = inStream.read(data, 0, data.length)) != -1) { 
    buffer.write(data, 0, nRead); 
} 

buffer.flush(); 

,並檢查使用:

assertEquals(buffer.toByteArray(), uniqueId.getBytes()); 
-2

爲什麼不嘗試這樣的事情?

@Test 
public void testStreamBytes() 
    throws PersistenceException, IOException, ClassNotFoundException { 
    final String uniqueId = "TestString"; 
    final byte[] written = uniqueId.getBytes(); 
    final byte[] read = new byte[written.length]; 
    try (final OutputStream outStream = fileService.getOutputStream(uniqueId)) { 
    outStream.write(written); 
    } 
    try (final InputStream inStream = fileService.getInputStream(uniqueId)) { 
    int rd = 0; 
    final int n = read.length; 
    while (rd <= (rd += inStream.read(read, rd, n - rd))) 
     ; 
    } 
    assertEquals(written, read); 
} 
+0

不起作用。您必須獨立於最後一次讀取計數前移偏移量。 – EJP