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  }

    效果:

  • 相关阅读:
    json.stringify()和json.parse()
    C# 对json对象嵌套数组
    sql 时间段内没有的数据等于0
    epoint:TreeView
    Asp.Net使用org.in2bits.MyXls.dll操作excel的应用
    VS中的生成事件
    mysql主从复制
    mysql索引优化分析
    MySQL逻辑架构简介
    大数据DMP画像系统(转载 简介-龙果学院)
  • 原文地址:https://www.cnblogs.com/gongxijun/p/3875729.html
Copyright © 2011-2022 走看看