【问题标题】:is this correct ? how to load bytes from a file? [duplicate]它是否正确 ?如何从文件中加载字节? [复制]
【发布时间】:2013-05-10 08:15:08
【问题描述】:

我需要使用 Java 从文件中加载字节。是这样吗?

InputStream ips=new FileInputStream(file); 
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);                 
String line;
String cle = "" ;
while ((line=br.readLine())!=null){
   cle+=line
}
---> cle.getBytes()

【问题讨论】:

标签: java file byte inputstream bufferedreader


【解决方案1】:

不,这绝对是不是这样做的方式:

  • 当您从文件中读取字节时,您正在将它们转换为文本
  • 您正在删除所有换行符(它们不是从readLine 返回的)
  • 您正在将文本转换回字节

这样很可能会丢失数据。

要加载 字节,您根本不应该使用 Reader - 只需使用 InputStream。理解二进制数据和文本数据不同是非常重要的。将它们中的任何一个视为另一个是一个非常糟糕的主意。

如果您只想读取文件中的所有数据,我会亲自使用Guava 及其Files 类:

byte[] data = Files.toByteArray(file);

或者,如果您已经拥有InputStream,请使用ByteStreams

byte[] data = ByteStreams.toByteArray(inputSTream);

这也适用于InputSupplier

【讨论】:

  • 我找到了这个RandomAccessFile f = new RandomAccessFile(file, "r"); byte[] cle = new byte[(int)f.length()]; f.read(cle); 好吗?
【解决方案2】:

我会使用 java.nio.file.Files.readAllBytes

 byte[] bytes = Files.readAllBytes(Paths.get(path));

【讨论】:

  • 我找到了这个RandomAccessFile f = new RandomAccessFile(file, "r"); byte[] cle = new byte[(int)f.length()]; f.read(cle); 好吗?
  • 不完全。 f.read(cle) 返回它读取的实际字节数。您应该继续阅读,直到它返回 -1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
相关资源
最近更新 更多