java 处理byte_java - 文件到Java中的byte [] - 堆栈内存溢出
===============>>#1 票数:1222
例:
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
===============>>#2 票数:460 已采纳
这取决于最适合您的方式。 明智地提高生产力,不要重蹈覆辙,而是使用Apache Commons。
===============>>#3 票数:181
从JDK 7开始-一种衬板:
byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));
无需外部依赖项。
===============>>#4 票数:161
import java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
===============>>#5 票数:76
基本上,您必须在内存中读取它。 打开文件,分配数组,然后将文件中的内容读入数组。
最简单的方法类似于以下内容:
public byte[] read(File file) throws IOException, FileTooBigException {
if (file.length() > MAX_FILE_SIZE) {
throw new FileTooBigException(file);
}
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
}finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
这对文件内容有一些不必要的复制(实际上,数据被复制了三次:从文件复制到buffer ,从buffer复制到ByteArrayOutputStream ,从ByteArrayOutputStream到实际的结果数组)。
您还需要确保仅在内存中读取最大大小的文件(通常取决于应用程序):-)。
您还需要在函数外部处理IOException 。
另一种方法是这样的:
public byte[] read(File file) throws IOException, FileTooBigException {
if (file.length() > MAX_FILE_SIZE) {
throw new FileTooBigException(file);
}
byte[] buffer = new byte[(int) file.length()];
InputStream ios = null;
try {
ios = new FileInputStream(file);
if (ios.read(buffer) == -1) {
throw new IOException(
"EOF reached while trying to read the whole file");
}
} finally {
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return buffer;
}
这没有不必要的复制。
FileTooBigException是自定义应用程序异常。 MAX_FILE_SIZE常量是一个应用程序参数。
对于大文件,您可能应该考虑使用流处理算法或使用内存映射(请参阅java.nio )。
===============>>#6 票数:72
public static byte[] readFileToByteArray(File file) throws IOException
用法示例( Program.java ):
import org.apache.commons.io.FileUtils;
public class Program {
public static void main(String[] args) throws IOException {
File file = new File(args[0]); // assume args[0] is the path to file
byte[] data = FileUtils.readFileToByteArray(file);
...
}
}
===============>>#7 票数:22
您也可以使用NIO API。 只要总文件大小(以字节为单位)适合int,我就可以使用此代码执行此操作。
File f = new File("c:\\wscp.script");
FileInputStream fin = null;
FileChannel ch = null;
try {
fin = new FileInputStream(f);
ch = fin.getChannel();
int size = (int) ch.size();
MappedByteBuffer buf = ch.map(MapMode.READ_ONLY, 0, size);
byte[] bytes = new byte[size];
buf.get(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fin != null) {
fin.close();
}
if (ch != null) {
ch.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
我认为自从使用MappedByteBuffer以来,它的速度非常快。
===============>>#8 票数:20
如果您没有Java 8,并同意我的观点,那么包含一个庞大的库以避免编写几行代码是一个坏主意:
public static byte[] readBytes(InputStream inputStream) throws IOException {
byte[] b = new byte[1024];
ByteArrayOutputStream os = new ByteArrayOutputStream();
int c;
while ((c = inputStream.read(b)) != -1) {
os.write(b, 0, c);
}
return os.toByteArray();
}
调用方负责关闭流。
===============>>#9 票数:19
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
throw new IOException("File is too large!");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
===============>>#10 票数:17
简单的方法:
File fff = new File("/path/to/file");
FileInputStream fileInputStream = new FileInputStream(fff);
// int byteLength = fff.length();
// In android the result of file.length() is long
long byteLength = fff.length(); // byte count of the file-content
byte[] filecontent = new byte[(int) byteLength];
fileInputStream.read(filecontent, 0, (int) byteLength);
===============>>#11 票数:14
从文件读取字节的最简单方法
import java.io.*;
class ReadBytesFromFile {
public static void main(String args[]) throws Exception {
// getBytes from anyWhere
// I'm getting byte array from File
File file = null;
FileInputStream fileStream = new FileInputStream(file = new File("ByteArrayInputStreamClass.java"));
// Instantiate array
byte[] arr = new byte[(int) file.length()];
// read All bytes of File stream
fileStream.read(arr, 0, arr.length);
for (int X : arr) {
System.out.print((char) X);
}
}
}
===============>>#12 票数:11
它涵盖了极端情况,即文件报告的长度为0但仍然包含内容
它经过高度优化,如果在尝试加载大文件之前尝试读入一个大文件,则会收到OutOfMemoryException。 (通过巧妙地使用file.length())
您不必重新发明轮子。
===============>>#13 票数:11
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
File file = getYourFile();
Path path = file.toPath();
byte[] data = Files.readAllBytes(path);
===============>>#14 票数:10
使用与社区Wiki答案相同的方法,但更加整洁且开箱即用(如果您不想导入Apache Commons lib,例如在Android上,则首选方法):
public static byte[] getFileBytes(File file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1)
ous.write(buffer, 0, read);
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
// swallow, since not that important
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
// swallow, since not that important
}
}
return ous.toByteArray();
}
===============>>#15 票数:7
我相信这是最简单的方法:
org.apache.commons.io.FileUtils.readFileToByteArray(file);
===============>>#16 票数:5
ReadFully从当前文件指针开始,将b.length个字节从此文件读取到字节数组中。 此方法从文件重复读取,直到读取了请求的字节数。 该方法将阻塞,直到读取请求的字节数,检测到流的末尾或引发异常为止。
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
===============>>#17 票数:4
如果要将字节读取到预分配的字节缓冲区中,此答案可能会有所帮助。
但是,此方法有一个缺陷,使其难以合理地使用:即使没有遇到EOF,也不能保证该数组实际上将被完全填充。
这是输入流的包装,没有上述问题。 此外,遇到EOF时将抛出此方法。 好多了。
===============>>#18 票数:3
public static byte[] readBytes(InputStream inputStream) throws IOException {
byte[] buffer = new byte[32 * 1024];
int bufferSize = 0;
for (;;) {
int read = inputStream.read(buffer, bufferSize, buffer.length - bufferSize);
if (read == -1) {
return Arrays.copyOf(buffer, bufferSize);
}
bufferSize += read;
if (bufferSize == buffer.length) {
buffer = Arrays.copyOf(buffer, bufferSize * 2);
}
}
}
===============>>#19 票数:3
当相互测试许多不同的Java文件读取方法时,以下方法不仅将java.io.File转换为byte [],而且还发现它是读取文件的最快方法:
java.nio.file.Files.readAllBytes()
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class ReadFile_Files_ReadAllBytes {
public static void main(String [] pArgs) throws IOException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
byte [] fileBytes = Files.readAllBytes(file.toPath());
char singleChar;
for(byte b : fileBytes) {
singleChar = (char) b;
System.out.print(singleChar);
}
}
}
===============>>#20 票数:3
让我添加一个不使用第三方库的解决方案。 它重新使用了Scott ( link )提出的异常处理模式。 然后将丑陋的部分移到单独的消息中(我将隐藏在某些FileUtils类中;))
public void someMethod() {
final byte[] buffer = read(new File("test.txt"));
}
private byte[] read(final File file) {
if (file.isDirectory())
throw new RuntimeException("Unsupported operation, file "
+ file.getAbsolutePath() + " is a directory");
if (file.length() > Integer.MAX_VALUE)
throw new RuntimeException("Unsupported operation, file "
+ file.getAbsolutePath() + " is too big");
Throwable pending = null;
FileInputStream in = null;
final byte buffer[] = new byte[(int) file.length()];
try {
in = new FileInputStream(file);
in.read(buffer);
} catch (Exception e) {
pending = new RuntimeException("Exception occured on reading file "
+ file.getAbsolutePath(), e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
if (pending == null) {
pending = new RuntimeException(
"Exception occured on closing file"
+ file.getAbsolutePath(), e);
}
}
}
if (pending != null) {
throw new RuntimeException(pending);
}
}
return buffer;
}
===============>>#21 票数:1
从文件读取字节的另一种方法
Reader reader = null;
try {
reader = new FileReader(file);
char buf[] = new char[8192];
int len;
StringBuilder s = new StringBuilder();
while ((len = reader.read(buf)) >= 0) {
s.append(buf, 0, len);
byte[] byteArray = s.toString().getBytes();
}
} catch(FileNotFoundException ex) {
} catch(IOException e) {
}
finally {
if (reader != null) {
reader.close();
}
}
===============>>#22 票数:0
尝试这个 :
try {
String path="";
InputStream inputStream=new FileInputStream(path);
byte[] data=IOUtils.readFully(inputStream,-1,false);
}
catch (IOexception e) {
System.out.println(e);
}
不要忘记“ 导入sun.misc.IOUtils; ”
===============>>#23 票数:-6
在JDK8中
Stream lines = Files.lines(path);
String data = lines.collect(Collectors.joining("\n"));
lines.close();
ask by Ben Noland translate from so
java 处理byte_java - 文件到Java中的byte [] - 堆栈内存溢出相关推荐
- java 构造器 null_java - 主结尾处的Java构造函数用户输入在构造函数中为Null - 堆栈内存溢出...
每次编写new Circle1()都会创建一个全新的对象,该对象与其他对象无关. 而当你这样做 Cercle1 pi = new Cercle1(); Cercle1 radius= new Cerc ...
- java获取excel文件第一行_java - 在Java中读取Excel文件,但第一行除外 - 堆栈内存溢出...
我正在尝试从使用xlsx文件的JasperReport模板自动创建报告,我用来从excel文件读取的方法是这样的: String[] columnNames = new String[]{" ...
- Java页码超出_java - 表中的页码 - 堆栈内存溢出
为此,创建一个文本运行,并在这些文本运行中插入字段"PAGE \\\\* MERGEFORMAT"和/或"NUMPAGES \\\\* MERGEFORMAT" ...
- 如何为linux 桌面文件内存,linux - 桌面Linux发行版中.desktop文件的功能是什么? - 堆栈内存溢出...
我有以下情况:我必须修改一个.desktop文件,该文件位于我正在使用的应用程序的包中. 当我尝试打开文件的内容时,我遇到了一个奇怪的问题. 如果我点击它然后我尝试点击"打开"它给 ...
- 组件文件已损坏或android内部模块,android - Android Q更新后,模块化系统组件在托管配置文件中不可用 - 堆栈内存溢出...
在从工作配置文件配置的设备设置应用中将操作系统从Android 9升级到10后,请停止运行. java.lang.RuntimeException: Unable to start activity ...
- python从html拿到数据,python - 使用BeautifulSoup和Python从HTML文件中提取数据 - 堆栈内存溢出...
我需要提取的数据可以在不同的标题下找到. 这是我到目前为止: from BeautifulSoup import BeautifulSoup ecj_data = open("data\ec ...
- abaqus的python安装文件在哪_python - 在ABAQUS 6.14 python环境中安装熊猫 - 堆栈内存溢出...
我想要做的是在ABAQUS CAE软件包内的python发行版中安装Pandas软件包. Python 2.7.3 (default, Oct 4 2012, 15:15:08) [MSC v.160 ...
- python ftp timeout_python - FTP文件传输期间Python数据通道超时 - 堆栈内存溢出
我正在尝试使用Python的ftplib传输文件. def ftps_put_file(host, user, password, ftp_file_path, processed_file): tr ...
- matlab两个数组竖向叠加,matlab - 过滤器同时使用两个数组中的元素 - 堆栈内存溢出...
解决这个问题的方法是找到一种方法来组合A和B中的信息,以便过滤本身变得容易. 我想到的第一件事是沿着第三维连接A和B,并使用过滤器掩码传递,该过滤器掩码将从'A-slice'获取8个元素,从'B-sl ...
最新文章
- R语言glmnet拟合岭回归模型实战:岭回归模型的模型系数(ridge regression coefficients)及可视化、岭回归模型分类评估计算(混淆矩阵、accuracy、Deviance)
- 曾经百度大佬吹过的牛实现了,看完这个,带你搞定AI前沿技术
- 【Todo】Java的JIT机制
- OpenCV下设置灰度直方图的阈值来对图像进行查找(查表)变换的源码
- 借由AI招聘软件,这位CEO 48h 内从4000名求职者中锁定那一位
- gc()两分钟了解JDK8默认垃圾收集器(附英文)
- 双系统引导修复与引导项删除
- 带有审图号的区位图制作
- matlab图像基础处理小记
- qt开发用的人多吗_新房认筹猫腻多!开发商只是为达到这个目的才认筹,你入坑了吗?...
- 税控服务器管理系统已签名未上传,增值税发票管理系统升级后发票上传失败、勾选平台插件设置、勾选签名问题、勾选规则等热点问题...
- win10远程桌面连接服务器接示内部错误
- 什么牌子的蓝牙耳机耐用?类似airpods pro的降噪耳机推荐
- Python 乘法口诀
- 【转】JAVA中Cookie MaxAge属性及其使用
- ART–KOHONEN neural network for fault diagnosis of rotating machinery(翻译)
- 对均匀采样信号进行重采样
- win 2008 创建密码重置盘
- .NET程序员的技能分析参考V1.0(有附件)
- vegeta 压测使用简单介绍
热门文章
- 创建springboot多模块项目
- java内部类的作用
- Qt QtConcurrent之 Run 函数用法
- XScuGic_Connect分析
- 计算机转集成光学,最新集成光学考试总结.docx
- opencv4版本和3版本_世界名曲鸽子最好听的3个版本,美醉了!
- 操作系统原理:中断,异常,系统调用
- 鸿蒙系统第一次出现,华为鸿蒙系统第三“用户”出现?没想到是它
- Cpp 对象模型探索 / 虚函数的调用方式
- c语言逻辑错误调试,c语言程序,现在出现逻辑错误,哪位高手指点下啊。。。...