关于文件输出流

构造器

image.png

方法一览

image.png

示例代码

  1. import java.io.FileOutputStream;
  2. import java.io.IOException;
  3. public class Main {
  4. public static void main(String[] args) {
  5. // 文件路径
  6. String path = "./write.txt";
  7. // true=追加、false=覆盖
  8. boolean append = true;
  9. FileOutputStream fos = null;
  10. try {
  11. // 创建流对象
  12. fos = new FileOutputStream(path,append);
  13. String str = "0123456789ABCDEFG\n";
  14. // 将 String 转换为 Byte 数组后,使用流对象写入文件
  15. fos.write(str.getBytes());
  16. fos.write(str.getBytes(), 0, str.length());
  17. fos.write(str.getBytes(), 0, 3);
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. } finally {
  21. // 关闭连接
  22. try {
  23. fos.close();
  24. } catch (IOException e) {
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. }