Demo02_FileOutputStream.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package J20250725;
  2. import java.io.FileNotFoundException;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.nio.charset.StandardCharsets;
  6. /**
  7. * @author WanJl
  8. * @version 1.0
  9. * @title Demo02_FileOutputStream
  10. * @description
  11. * @create 2025/7/25
  12. */
  13. public class Demo02_FileOutputStream {
  14. public static void main(String[] args) throws IOException {
  15. FileOutputStream fos = null;
  16. //append参数 表示是否能够追加数据,true为是
  17. fos = new FileOutputStream("Z:/2025年7月25日.txt", true);
  18. String s = "你好,世界!!!";
  19. byte[] bytes = s.getBytes();
  20. fos.write(bytes);
  21. byte[] bytes1 = "12345678910".getBytes();
  22. fos.write(bytes1, 3, 5);
  23. fos.write("今天".getBytes());
  24. fos.write("\r\n".getBytes()); //Windows系统换行 \r\n
  25. fos.write("天儿挺好".getBytes());
  26. fos.close();
  27. }
  28. /*
  29. public static void main(String[] args){
  30. FileOutputStream fos=null;
  31. try {
  32. //append参数 表示是否能够追加数据,true为是
  33. fos=new FileOutputStream("Z:/2025年7月25日.txt",true);
  34. String s="你好,世界!!!";
  35. byte[] bytes = s.getBytes();
  36. fos.write(bytes);
  37. byte[] bytes1 = "12345678910".getBytes();
  38. fos.write(bytes1,3,5);
  39. fos.write("今天".getBytes());
  40. fos.write("\r\n".getBytes()); //Windows系统换行 \r\n
  41. fos.write("天儿挺好".getBytes());
  42. } catch (FileNotFoundException e) { //先处理文件找不到异常
  43. System.out.println("文件找不到了,我们要再这里进行相关的处理,找到文件");
  44. }catch (IOException e){ //再处理IO异常
  45. System.out.println("文件找到了,但是没有权限向文件读写数据,这里我们要做相关处理");
  46. }finally {
  47. //关闭流
  48. try {
  49. fos.close();
  50. } catch (IOException e) { //处理IO异常
  51. System.out.println("关闭流的时候,IO异常发生了,我们这里要做相关处理保证关闭流或做其他操作");
  52. }catch (Exception e){
  53. System.out.println("出现异常了.....我也不知道什么异常,反正要处理");
  54. }
  55. }
  56. //程序后续要执行的代码.......
  57. for (int i = 0; i < 1000; i++) {
  58. System.out.println("Hello "+i);
  59. try {
  60. Thread.sleep(1000);
  61. } catch (InterruptedException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. */
  67. }