簡體   English   中英

將所有標准輸入讀入Java字節數組

[英]Read all standard input into a Java byte array

在現代Java中(僅使用標准庫)最簡單的方法是將所有標准輸入讀取到EOF直到字節數組,最好不必自己提供該數組? stdin數據是二進制數據,不是來自文件。

即像Ruby的東西

foo = $stdin.read

我能想到的唯一的部分解決方案是

byte[] buf = new byte[1000000];
int b;
int i = 0;

while (true) {
    b = System.in.read();
    if (b == -1)
        break;
    buf[i++] = (byte) b;
}

byte[] foo[i] = Arrays.copyOfRange(buf, 0, i);

...但這甚至對於Java來說似乎也很冗長,並且使用固定大小的緩沖區。

我將使用Guava及其ByteStreams.toByteArray方法:

byte[] data = ByteStreams.toByteArray(System.in);

在不使用任何第三方庫的情況下,我將使用ByteArrayOutputStream和一個臨時緩沖區:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[32 * 1024];

int bytesRead;
while ((bytesRead = System.in.read(buffer)) > 0) {
    baos.write(buffer, 0, bytesRead);
}
byte[] bytes = baos.toByteArray();

...可能將其封裝在接受InputStream的方法中,該方法基本上等同於ByteStreams.toByteArray ...

如果您正在讀取文件,則使用Files.readAllBytes即可。

否則,我將使用ByteBuffer:

ByteBuffer buf = ByteBuffer.allocate(1000000);
ReadableByteChannel channel = Channels.newChannel(System.in);
while (channel.read(buf) >= 0)
    ;
buf.flip();
byte[] bytes = Arrays.copyOf(buf.array(), buf.limit());

暫無
暫無

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

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