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));
        }
    }
  • 相关阅读:
    当tp5项目上传到服务器之后遇见的各种bug(不定期更新)
    解决LAMP下 服务器IP无法访问
    thinkphp5多图上传+同时删除本地文件
    from提交表单后 数据提交到后台 但不跳转页面 非ajax 用iframe
    window7 安装sass和compass
    开源操作系统课程设计
    Hadoop伪分布式搭建实验总结
    排序集合
    快排
    邻接矩阵
  • 原文地址:https://www.cnblogs.com/weibanggang/p/10034462.html
Copyright © 2011-2022 走看看