zoukankan      html  css  js  c++  java
  • java中io创建文件和读取文件

    简单了解IO流:https://www.cnblogs.com/weibanggang/p/10034325.html

    package com.wbg.iodemo1128;
    
    import java.io.*;
    
    public class OutputStreamDemo {
        public static void main(String[] args) throws IOException {
            reader();
        }
        //输入字节流inputStream
        static void inputStream() throws IOException {
            File f=new File("F:"+File.separator+"test01.txt");
            InputStream inputStream=new FileInputStream(f);
            byte b[]=new byte[1024];
            inputStream.read(b);
            inputStream.close();
            System.out.println(new String(b));
        }
        //输出字节流OutputStream
        static void outputStream()throws IOException{
            //第一步:使用File找到一个文件
            File f=new File("F:"+File.separator+"test01.txt");
            //创建文件
            f.createNewFile();
            //第二步:通过子类实例化父类对象
            OutputStream out=new FileOutputStream(f);
            //第三步:写一个字符串
            String str="Hello World!!!";
            //第四步:字符串转为byte数组
            byte b[]=str.getBytes();
            //第五步:内容输出
            out.write(b);
            //第六步:关闭
            out.close();
        }
        //字符流输出
        static void writer() throws IOException {
            //第一步:使用File找到一个文件
            File f=new File("f:"+File.separator+"test.txt");
            //第二步:通过子类实例化父类对象
            Writer out=new FileWriter(f);
            //追加
           // Writer out=new FileWriter(f,true);
            //第三:定义字符串
            String str="Hello,Word!!!";
            //第四步:输出
            out.write(str);
            //第五步:强制清空缓存
            out.flush();
            //第六步:关闭
             out.close();
        }
        //字符流正常输入
        static void reader() throws IOException {
            //第一步:使用File找到一个文件
            File f=new File("f:"+File.separator+"test.txt");
            Reader readerout=new FileReader(f);
            int len=0;
            char[]c=new char[1024];
            int temp=0;
            while ((temp=readerout.read())!=-1){
                c[len]=(char)temp;
                len++;
            }
            readerout.close();
            System.out.println(new String(c,0,len));
        }
        //字符流输入追加
        static void readerAdd() throws IOException {
            File f=new File("f:"+File.separator+"test.txt");
            Reader reader=new FileReader(f);
            char[]c=new char[(int)f.length()];
            reader.read(c);
            reader.close();
            System.out.println(new String(c));
        }
    }
  • 相关阅读:
    超强视频分割/剪辑软件-Ultra Video Splitter绿色便携版
    超强视频分割/剪辑软件-Ultra Video Splitter绿色便携版
    ASP.NET做WEB开发的工具选择
    ASP.NET做WEB开发的工具选择
    C#中的局部类型
    OpenCV2:幼儿园篇 第四章 访问图像
    OpenCV2:幼儿园篇 第三章 导出图像
    OpenCV2:幼儿园篇 第二章 读取图像
    OpenCV2:幼儿园篇 第一章 创建图像并显示
    MFC隐藏在黑暗之中的大坑
  • 原文地址:https://www.cnblogs.com/weibanggang/p/10034462.html
Copyright © 2011-2022 走看看