zoukankan      html  css  js  c++  java
  • 将文件字节输出流写入到文本中

     1 package DEMO;
     2 
     3 import java.io.File;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.OutputStream;
     7 import java.util.Scanner;
     8 
     9 /*
    10  *   文件字节输出流  2014-7-29
    11  *   1.给出输出流的目的地
    12  *   2.创建指向目的地的输出流
    13  *   3.人输出流把数据写入到目的地
    14  *   4.关闭输出流 
    15  *   
    16  *   举例:  使用文件输出流写文件a.txt
    17  *   措施:首先使用具有刷新功能的构造方法创建指向文件a.txt的输出流,
    18  *   并向a.txt文件写入“新年快乐”,然后在选择使用不刷新文件的构造方法
    19  * 
    20  *   指向a.txt。并向文件写入(即尾加),"happy New Year !"。
    21  */
    22 
    23  public class  test
    24  {
    25      public static void main(String args [])
    26      {
    27         /*byte [] a="新年快乐".getBytes();*/
    28         byte [] a= new byte [100];
    29         Scanner reader=new Scanner(System.in);
    30          int i=0;
    31         while(reader.hasNext())
    32             a=reader.next().getBytes();
    33          byte [] b ="happy New Year".getBytes();
    34          File file = new File("a.txt");
    35          if(!file.exists())
    36          {  
    37             //如果不存在,则在指定的目录下创建一个a.txt;
    38              try {
    39                 file.createTempFile("Gxjun", ".java") ;
    40             } catch (IOException e) {
    41                 // TODO Auto-generated catch block
    42                 e.printStackTrace();
    43             }
    44          }
    45          try {
    46               OutputStream out= new FileOutputStream(file);   //输出的目的地
    47               System.out.println(file.getName()+"的大小:"+file.length()+"字节");
    48               out.write(a);
    49              out.close();
    50              out= new FileOutputStream(file,true);  //不刷新,准备向文件尾加内容
    51              System.out.println(file.getName()+"的大小:"+file.length());
    52              out.write(b,0,b.length);
    53              System.out.println(file.getName()+"的大小:"+file.length()+"字节");
    54                                              //a.txt的大小:22字节
    55              out.close();
    56         } catch (IOException e) {
    57             // TODO Auto-generated catch block
    58             e.printStackTrace();
    59         }    
    60  }
    61  }

    效果:

  • 相关阅读:
    socket http tcp udp ip 协议
    docker启动报错iptables failed: -重建docker0网络恢复
    python3处理json数据
    nginx添加认证
    安装nginx和nginx-gridfs和mongodb
    Centos7下CPU内存等资源监控
    linux 中 iptables关于ping的问题
    python3和pip3安装和问题解决
    Centos7下安装zabbix 3.0.19
    ansible学习网站
  • 原文地址:https://www.cnblogs.com/gongxijun/p/3875729.html
Copyright © 2011-2022 走看看