麒麟正青春

 

Java文件与byte数组

读取Java文件到byte数组的三种方式

一、FileUtils.java
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class FileUtils {

/**
*
* @param filePath
* @return
* @throws IOException
*/
public byte[] getContent(String filePath) throws IOException {

File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
  System.out.println("file too big...");
  return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
  offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
  throw new IOException("Could not completely read file " + file.getName());
}
fi.close();
return buffer;

}

/**
* the traditional io way
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filename) throws IOException {

File f = new File(filename);
if (!f.exists()) {
  throw new FileNotFoundException(filename);
}

ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {

in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
  bos.write(buffer, 0, len);
}
return bos.toByteArray();

} catch (IOException e) {
  e.printStackTrace();
  throw e;
} finally {
  try {
  in.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
  bos.close();
}

}

/**
* NIO way
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filename) throws IOException {

  File f = new File(filename);
  if (!f.exists()) {
    throw new FileNotFoundException(filename);
  }

  FileChannel channel = null;
  FileInputStream fs = null;
  try {
    fs = new FileInputStream(f);
    channel = fs.getChannel();
    ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
    while ((channel.read(byteBuffer)) > 0) {
      // do nothing
      // System.out.println("reading");
  }
  return byteBuffer.array();
 } catch (IOException e) {
  e.printStackTrace();
  throw e;
 } finally {
  try {
    channel.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
  try {
    fs.close();
  } catch (IOException e) {
    e.printStackTrace();
  }
 }
}

/**
* Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray3(String filename) throws IOException {

FileChannel fc = null;
try {
fc = new RandomAccessFile(filename, "r").getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
System.out.println(byteBuffer.isLoaded());
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
  // System.out.println("remain");
  byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;

} catch (IOException e) {
  e.printStackTrace();
  throw e;
} finally {
  try {
    fc.close();
  } catch (IOException e) {
  e.printStackTrace();
}

}

}

}
文章知识点与官方知识档案匹配,可进一步学习相关知识
————————————————
版权声明:本文为CSDN博主「Tzq@2018」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tttzzzqqq2018/article/details/132613467

/**
* 将字节数组写入文件
* byte[] byteArray 这里是你的字节数组
* @param filename "文件路径/文件名"
* */
public static void byteArrayToFile(byte[] byteArray,String filename)
{

  // 这里是你的字节数组

//byte[] byteArray =null;
FileOutputStream outputStream = null;

try {
  outputStream = new FileOutputStream(filename);//"文件路径/文件名"
  outputStream.write(byteArray);
} catch (IOException e) {
  e.printStackTrace();
} finally {
  if (outputStream != null) {
    try {
      outputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
}

}

//使用Java的FileOutputStream类将字节数组写入到一个文件中。
//在代码中,首先定义了一个字节数组byteArray。
// 然后,创建了一个FileOutputStream对象,将要写入的文件路径和文件名传递给它。
// 接下来,使用write()方法将字节数组写入到文件中。
// 最后,一定要关闭输出流以释放资源。
// 如果出现任何异常,可以在catch块中捕获并处理它们。

// 作者:lcf
// 链接:https://www.zhihu.com/question/583443292/answer/2888746618
// 来源:知乎
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

posted on 2023-12-21 15:15  麒麟正青春  阅读(208)  评论(0编辑  收藏  举报

导航