zoukankan      html  css  js  c++  java
  • 输入输出—输出和读入文本

     1 package shurushuchuliu;
     2 import java.io.*;
     3 public class Test3 {
     4 
     5     public static void main(String[] args) {
     6         try {
     7             // 准备文件对象
     8             File file = new File("d:/test.txt");
     9             
    10 
    11             // 如果不存在
    12             if (!file.exists()) {
    13                 //创建文件
    14                 file.createNewFile();
    15                 System.out.println("创建文件成功");
    16             }
    17             // 构造字节输出流,指定目标文件
    18             //覆盖方式写入
    19             FileOutputStream fos = new FileOutputStream(file,true);
    20             String str="这是文件写入内容
    ";
    21             String str11="
    这是文件写入内容";
    22             String str12="
    这是文件写入内容";
    23 
    24             //数据,把数据源转换成byte[](byte数组).    byte:字节
    25             byte[] b=str.getBytes();
    26             
    27             //写入数据
    28             fos.write(b);
    29             //关闭流,释放文件
    30             fos.close();
    31             System.out.println("
    写入文件完成");
    32             
    33             System.out.println("FileInputStream输入流");
    34             //字节输入流
    35             FileInputStream fis=new FileInputStream(file);
    36             //装载读入的数据     初始化数据
    37             //引用类型
    38             //传递的是变量的地址
    39             byte[] d=new byte[1024];
    40             //全部内容
    41             String str2="";
    42             //写入数据     返回值int型:代表读入数据的长度
    43             //int i=fis.read(d);
    44             //循环读
    45 //            while(i>0)
    46 //            {
    47 //                //从byte型数组(byte[])装换成需要的类型
    48 //            String str1=new String(d,0,i);
    49 //            str2+=str1;
    50 //            //继续读
    51 //            i=fis.read(d);
    52 //            }
    53             int i=0;
    54             while((i=fis.read(d))>0)
    55             {
    56                 //从byte型数组(byte[])装换成需要的类型
    57             String str1=new String(d,0,i);
    58             str2+=str1;
    59             //继续读
    60             //i=fis.read(d);
    61             }
    62             
    63             System.out.println("读入的内容="+str2);
    64             //关闭
    65             fis.close();
    66             
    67         } catch (Exception e) {
    68             // TODO 自动生成的 catch 块
    69             e.printStackTrace();
    70         }
    71 
    72     }
    73 
    74 }
  • 相关阅读:
    不准再问我:最近过的怎么样
    嫌疑人X的献身
    关于生活
    怎么可以这样
    在WPF中动态使用图片和按钮
    MFC 中获取对话框中控件焦点的方法
    MessageBox的常见用法
    拖拽(待完善版)
    Baidu Suggestion 百度搜索(仅功能实现,烂版)
    如何判断一个对象是Element?
  • 原文地址:https://www.cnblogs.com/yg6405816/p/5548484.html
Copyright © 2011-2022 走看看