读取磁盘文件输入流

  1. // import java.io.*;
  2. public static void readFile(String[] args){
  3. // 获取文件
  4. String filePath = "/home/README.md";
  5. File file = new File(filePath);
  6. // 借助 BufferedInputStream() 起到缓冲作用
  7. try(InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  8. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"))){
  9. String line;
  10. StringBuilder sb = new StringBuilder();
  11. while((line = br.readLine()) != null){
  12. sb.append(line);
  13. }
  14. // stream handler ...
  15. } catch(IOException e){
  16. // IOException handler ...
  17. }
  18. }

输出(动态追加)文件

  1. // import java.io.*;
  2. public static void writeFile(String[] args) {
  3. String outputFilePath = "/home/README.md";
  4. try (FileOutputStream fileOutputStream = new FileOutputStream(outputfilePath, true);
  5. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) {
  6. // 使用 str 字符串代替多文本文件
  7. String str = "str ...";
  8. bufferedOutputStream.write(sql.getBytes("UTF-8"), 0, str.getBytes().length);
  9. bufferedOutputStream.write(str.getBytes("UTF-8"));
  10. bufferedOutputStream.flush();
  11. } catch (IOException e) {
  12. // IOException handler ...
  13. }
  14. }

备注: .flush() 作用:

flush() 这个函数是清空的意思,用于清空缓冲区的数据流,进行流的操作时,数据先被读到内存中,然后再用数据写到文件中,那么当你数据读完时,我们如果这时调用close()方法关闭读写流,这时就可能造成数据丢失,为什么呢,因为,读入数据完成时不代表写入数据完成,一部分数据可能会留在缓存区中,为了理解这个问题,我们举一个例子:

比如,在农村,几乎每家都有抽水机,抽水机的作用是什么呢,就是把水井里的水抽到水缸中,这时我们就会用水管连接抽水机和水缸(水管就好比是缓冲区),当我们想把水井中的水都抽到水缸中时,我们就让抽水机工作抽水,如果我们发现水井里的水刚好抽完时,我们就会关掉抽水机的开关停止抽水,那么这时,管道里就会遗留一部分水,抽水就是读数据,水缸进水就是写数据,水管充当缓存区的角色,不知道这样是不是具象化了呢

那么这样一来我们如果中途调用close()方法,输出区也还是有数据的,就像水缸里有水,只是在缓冲区遗留了一部分,这时如果我们先调用flush()方法,就会强制把数据输出,缓存区就清空了,最后再关闭读写流调用close()就完成了。

说明: 在 try-catch-resource 语句中使用 new FileOutputStream(String name, boolean append) 构造函数实现文件动态追加功能。源码如下:

  1. /**
  2. * Creates a file output stream to write to the file with the specified
  3. * name. If the second argument is <code>true</code>, then
  4. * bytes will be written to the end of the file rather than the beginning.
  5. * A new <code>FileDescriptor</code> object is created to represent this
  6. * file connection.
  7. * <p>
  8. * First, if there is a security manager, its <code>checkWrite</code>
  9. * method is called with <code>name</code> as its argument.
  10. * <p>
  11. * If the file exists but is a directory rather than a regular file, does
  12. * not exist but cannot be created, or cannot be opened for any other
  13. * reason then a <code>FileNotFoundException</code> is thrown.
  14. *
  15. * @param name the system-dependent file name
  16. * @param append if <code>true</code>, then bytes will be written
  17. * to the end of the file rather than the beginning
  18. * @exception FileNotFoundException if the file exists but is a directory
  19. * rather than a regular file, does not exist but cannot
  20. * be created, or cannot be opened for any other reason.
  21. * @exception SecurityException if a security manager exists and its
  22. * <code>checkWrite</code> method denies write access
  23. * to the file.
  24. * @see java.lang.SecurityManager#checkWrite(java.lang.String)
  25. * @since JDK1.1
  26. */
  27. public FileOutputStream(String name, boolean append) throws FileNotFoundException {
  28. this(name != null ? new File(name) : null, append);
  29. }

BufferedImage 转 InputStream

ByfferedImage 转换成 InputStrean 输入流可以借助 ByteArrayOutputStream

先将 ByfferedImage 转换成 ByteArrayOutputStream 然后再调用 ByteArrayOutputStrean.toByteArray() 方法转换成字节数组即可。

看一个示例,该示例是截取系统屏幕,将截取的图片转换成输入流:

  1. import javax.imageio.ImageIO;
  2. import java.awt.*;
  3. import java.awt.image.BufferedImage;
  4. import java.awt.image.ColorModel;
  5. import java.io.*;
  6. // ...
  7. //获取全屏截图,截图类型为BufferedImage
  8. BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
  9. //创建储存图片二进制流的输出流
  10. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  11. //将二进制数据写进ByteArrayOutputStream
  12. ImageIO.write(image, "jpg", byteArrayOutputStream);
  13. // ByteArrayOutputStream 转 InputStream
  14. InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());