文件流

来源:互联网 发布:php 字节 编辑:程序博客网 时间:2024/05/17 02:05
在字节流中,暂时不要使用中文.
FileInputStream:     文件的字节输入流
FileOutputStream:  文件的字节输出流
FileReader:文件的字符输入流

FileWriter:文件的字符输出流

文件字节输入流:

public class FileInputStreamDemo {public static void main(String[] args) throws Exception {//1.创建源File f = new File("file/stream.txt");//2.创建文件字节输入流对象InputStream in = new FileInputStream(f);//3.具体的读写操作/** * int read(): * int read(byte[] b): * int read(byte[] b,int off,int len): */byte[] buffer = new byte[8];System.out.println(Arrays.toString(buffer));/*int ret = in.read(buffer);String str = new String (buffer,0,7);System.out.println(str);System.out.println(Arrays.toString(buffer));*/int ret = in.read(buffer,2,6);System.out.println(Arrays.toString(buffer));/*int len = -1;while((len = in.read(buffer))!=-1){String str = new String (buffer,0,len);System.out.println(str);}*/in.close();}}

文件字节输出流:

public class FileOutputStreamDemo {public static void main(String[] args) throws Exception {//1.创建目标对象(数据保存到哪一个文件)File targe = new File("file/stream.txt");//2.创建文件字节输出流对象OutputStream out = new FileOutputStream(targe,true);//3.具体的输出操作/** * void write(int b):把一个字节写出到文件中 * void write(byte[] b):把数组b中的所有的字节都写出到文件中 * void write(byte[] b, int off,int len):把数组中的从索引off开始的len个字节写出到文件中 * */out.write("abcdefghijklmn".getBytes(),5,4);//关闭资源out.close();}}

使用文件字符流完成文件的拷贝(纯文本文件):

public class FileCopyDemo {public static void main(String[] args) throws Exception {//1.创建源或目标文件File srcFile = new File("file/aa.txt");File destFile = new File("file/aa_copy.txt");//2.穿建输入流和输出流对象Reader in = new FileReader(srcFile);Writer out = new FileWriter(destFile);//读和写操作char[] buffer = new char[100];int len = -1;while((len = in.read(buffer))!=-1){out.write(buffer,0,len);}//关闭流out.close();in.close();}}


原创粉丝点击