java中有关文件流的操作

文件流: 顾名思义,程序和文件打交道.

此时我们谈及的文件,值得是纯文本文件(txt的,不要使用Word,Excel),


在字节流中,暂时不要使用中文.
FileInputStream: 文件的字节输入流
FileOutputStream: 文件的字节输出流
FileReader:文件的字符输入流
FileWriter:文件的字符输出流

文件字符流:

文件的字节流:
FileInputStream:
FileOutputStream:

使用字节流操作汉字或特殊的符号语言的时候,容易乱码,建议使用字符流.
先有字节流,后有字符流,字符流是对字节流的补充.

使用记事本打开某个文件,可以看到内容的就是文本文件,否则可以理解二进制.
一般的,操作二进制文件(图片,音频,视频等)必须使用字节流.
一般的,操作文本文件使用字符流.
如果不清楚是哪一类型文件,使用字节流.

文件的字符流:
FileReader:
FileWriter:

代码:

文件字节输入流:

    public static void main(String[] args) throws IOException {
        File file = new File("file/stream.txt");
        InputStream in =new FileInputStream(file);
        File fileCopy = new File("file/streamCopy.txt");
        OutputStream out = new FileOutputStream(fileCopy);
        //System.out.println(in.read());
/*      int read 读取一个字节,返回读取的字节
        int read(byte[] b)读取多个字节,并存储到数组中
        int read(byte[] b, int off, int len) */
        byte[] b = new byte[11];
/*      
 *      输出文件内容方式一
 *      in.read(b);
        String str = new String(b);
        System.out.println(str);*/
        //System.out.println(Arrays.toString(b));打印结果为Unicode编码
        //输出文件内容方式二
        int len = -1;//-1表示文件读取到最后
        while((len = in.read(b))!=-1){
            String str = new String(b,0,len);
            //文件拷贝
            out.write(b,0,len);
            System.out.println(str);
        }
        in.close();
    }

文件字节输出流:

    public static void main(String[] args) throws Exception {
        //文件可以帮我创建但是目录不能够帮我们创建,点解file文件夹refresh刷新file文件夹
        File file = new File("file/stream.txt");//如果文件不存在会自动创建刷新项目文件可以看见出现该文件了
        //获取FileOutputStream文件输出流对象,false表示不追加,true向文件中追加内容
        OutputStream out = new FileOutputStream(file,false);
        //在write方法中传入的参数为int或者是Byte如果传入的是int常量为65则转为A
        out.write("hello java!".getBytes());
/*      write(int b);把一个字节写出到文件中
        write(byte[] b, int off, int len);从b数组中的第off位置开始向文件中写入len位数字*/
        out.close();
    }
}

文件字符输出流:

package IO;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class CharReaderDemo {
    public static void main(String[] args) throws Exception {
        //获取源文件
        File file = new File("file/aaa.txt");
        //获取流对象
        Reader reader = new FileReader(file);
        int len = -1;
        //每次只能读取5个字符
        char[] cnt = new char[5];
        while((len = reader.read(cnt)) != -1){
            System.out.println(cnt);
        }
    }
}

文件字符输入流:

package IO;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class CharWriteDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("file/aaa.txt");
        //如果想追加内容设为true,否则或者默认为false
        Writer out = new FileWriter(file,true);
        String str = "我是新添加的字符串";
        char[] c= str.toCharArray();
        out.write(c);
        out.close();
    }
}

文件拷贝操作和资源的正确关闭:

文件拷贝:

package IO;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class FileCopy {
    public static void main(String[] args) throws IOException {
        //获取源
        File srcfile = new File("file"); 
        File[] files = srcfile.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return (new File(dir,name).isFile()&&name.endsWith(".txt"));
            }
        });
        File newFile = new File("new/copyFile.txt");
        OutputStream out = new FileOutputStream(newFile,true);
        System.out.println("------------写入操作---------------");
        for (File file : files) {
            System.out.println("文件名"+file.getName());
            InputStream in  = new FileInputStream(file);
            int len = -1;
            byte[] b = new byte[10];
            len = in.read(b);
            while(len != -1){
                String fileContent = new String(b);
                System.out.println("文件内容"+fileContent+"有效长度"+len);
                out.write(b, 0, len);
                len = in.read(b);
            }
            in.close();
        }
        InputStream in1 = new FileInputStream(newFile);
        int len = -1;
        byte[] B = new byte[1024];
        System.out.println("----------输出拷贝后的文件内容-----------------");
        while((len = in1.read(B)) != -1){
            String str = new String(B);
            System.out.println(str);
        }
        in1.close();
        out.close();
    }
}

资源的正确关闭:
这里写图片描述

文件字节流使用案例:
案例1:文件拷贝案例-拷贝指定目录的指定类型文件到指定目录.
分析: 比如把C:/java目录中所有的java文件拷贝到D:/text/把拷贝的所有文件的拓展名改为.txt.
这里写图片描述
案例2:获取进程数据-编译和运行Java代码.

package IO;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class dynamicCompile {
    public static void main(String[] args) throws IOException {
        String str = "System.out.println(\"hello word!\")";
        exec(str);

    }
    static void exec(String str) throws IOException{
        //1.获取源文件
        File file = new File("file/Hello.java");
        //2.拼接一个完整的程序
        StringBuilder sb = new StringBuilder();
        sb.append("public class Hello {");
        sb.append("public static void main(String [] args) {").append(str).append(";").append("}}");
        //3.保存到hello.java文件中
        OutputStream out = new FileOutputStream(file);
        byte[] b = new byte[100];
        out.write(sb.toString().getBytes());
        out.close();
        //4.读取javac进程来编译hello.java
        String command = "javac Hello.java";
        Process javacProcess = Runtime.getRuntime().exec(command);
        //5.读取javac进程中的错误流信息
        InputStream error = javacProcess.getErrorStream();
        //6. 读取流中的数据
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = error.read(buffer)) != -1){
            String msg = new String(buffer, 0, len);
            System.out.println(msg);
        }
        error.close();
        //7.调用java进程来运行hello.class
        Process javaProcess = Runtime.getRuntime().exec("java Hello");
        //8.读取进程中的流信息
        InputStream info = javaProcess.getInputStream();
        while((len = info.read(buffer)) !=-1){
            String msg = new String(buffer, 0, len);
            System.out.println(msg);
        }
        info.close();
        //9.删除java和class文件
        file.delete();
    }
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值