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));
        }
    }
  • 相关阅读:
    Erlang/OTP:基于Behaviour的回调函数
    使用ACE创建进程
    linux查看硬件信息
    测试~~
    很好的:纠错函数linux
    转帖
    sss
    转帖
    普通函数、虚函数、纯虚函数、
    ACE_Event_Handle
  • 原文地址:https://www.cnblogs.com/weibanggang/p/10034462.html
Copyright © 2011-2022 走看看