IO流操作

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/** I/O工具   以流的形式获取*/
public class IOUtil {

  private static final int DEFAULT_BUFFER_SIZE = 8192;

  private IOUtil() {}

  /**
   * 转换输入流为字节数组
   *
   * @param inputStream 输入流
   * @return 字节数组
   * @throws IOException 读取字节失败、关闭流失败等
   */
  public static byte[] toByteArray(InputStream inputStream) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;
    byte[] data = new byte[DEFAULT_BUFFER_SIZE];
    while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, nRead);
    }

    return buffer.toByteArray();
  }

  /**
   * 转换输入流为字符串
   *
   * @param inputStream 输入流
   * @return UTF-8编码的字符串
   * @throws IOException 读取字节失败、关闭流失败等
   */
  public static String toString(InputStream inputStream) throws IOException {
    return new String(toByteArray(inputStream), StandardCharsets.UTF_8);
  }

  /**
   * 从文件路径中读取字符串
   *
   * @param path 文件路径
   * @return UTF-8编码的字符串
   * @throws IOException 读取字节失败、关闭流失败等
   */
  public static String loadStringFromPath(String path) throws IOException {
    try (InputStream inputStream = Files.newInputStream(Paths.get(path))) {
      return toString(inputStream);
    }
  }
}

// 文件读取

public class Files {


    /**
     * @param fileName:
     * @return byte  jdk 7之后写法
     * @author Administrator
     * @description TODO 以byte【】的方式读取文件
     * @date 2023/2/14 0014 14:17
     */
    public static byte[] readFileByBytes(String fileName) throws IOException {
        try (InputStream in = new BufferedInputStream(new FileInputStream(fileName)); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] bytes = new byte[in.available()];
            for (int i = 0; (i = in.read(bytes)) != -1; ) {
                out.write(bytes, 0, i);
            }
            return out.toByteArray();
        }
    }


    /**
     * @param fileName:
     * @param bytes:
     * @param append:
     * @return void
     * @author Administrator
     * @description TODO 向文件写入byte【】
     * @date 2023/2/14 0014 14:27
     */
    public static void writeFileByBytes(String fileName, byte[] bytes, boolean append) throws IOException {
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName, append))) {
            out.write(bytes);
        }
    }

    public static void writeFileByBytes(String fileName, byte[] bytes) throws IOException {
        writeFileByBytes(fileName, bytes, false);
      //  IntStream.range(0,3).forEach();
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容