一、Java I/O 概述
Java 中包括两种输入输出流,分为字节流和字符流。其中字节流以字节为单位来进行处理输入输出操作,而字符流则以字符为单位进行处理输入输出操作。
字节流是最基本的,所有的 InputStream 和 OutputStream 的子类都是, 主要用在处理二进制数据,它是按字节来处理的
但实际中很多的数据是文本,又提出了字符流的概念,它是按虚拟机的 encode 来处理,也就是要进行字符集的转化
这两个之间通过 InputStreamReader,OutputStreamWriter 来关联,实际上是通过 byte[] 和 String 来关联
在实际开发中出现的汉字问题实际上都是在字符流和字节流之间转化不统一而造成的
在从字节流转化为字符流时,实际上就是 byte[] 转化为 String 时,
public String(byte bytes[], String charsetName)
有一个关键的参数字符集编码,通常我们都省略了,那系统就用操作系统的 lang
而在字符流转化为字节流时,实际上是 String 转化为 byte[] 时,
byte[] String.getBytes(String charsetName)
也是一样的道理
至于 java.io 中还出现了许多其他的流,按主要是为了提高性能和使用方便,
如 BufferedInputStream,PipedInputStream 等
二、主要类和其主要方法
1.File 类
主要方法见下面代码:
- import java.io.File;
- import java.io.IOException;
- /**
- *
- * @author fengkuirui
- * @date 2017-02-09
- * File类的主要方法测试;
- */
- public class FileTest {
- public static void main(String[] args) throws IOException {
- File file = new File(".");//当前路径创建File对象;
- //输出文件名
- System.out.println(file.getName());//.
- //输出当前文件的绝对路径
- System.out.println(file.getAbsoluteFile());//D:\JAVA\SE\IO\.
- //获取相对路径得父路径
- System.out.println(file.getParent());//null
- //获取上一级目录
- System.out.println(file.getAbsoluteFile().getParent());//D:\JAVA\SE\IO
- //在当前路径下创建一个临时文件
- File temp = File.createTempFile("aaa",".txt",file);
- //指定当JVM退出时删除文件
- temp.deleteOnExit();
- //以当前时间作为新的文件名创建新文件
- File file2 = new File(System.currentTimeMillis()+"");
- //判断新建文件是否存在
- System.out.println(file2.exists());//false
- //用其创建文件
- file2.createNewFile();
- //创建目录
- file2.mkdir();
- //使用list()方法列出当前路径下的所有文件和路径
- String[] fileList = file.list();
- System.out.println("当前路路径下的所有文件和目录");
- for(String f : fileList){
- System.out.println(f);
- }
- //listRoot()静态的方法列出所有的磁盘根目录
- File[] roots = File.listRoots();
- System.out.println("==系统所有的根路径如下:");
- for(File root : roots){
- System.out.println(root);
- }
- System.out.println();
- }
- }
运行结果如下:
2.、FileInputStream 和 FileoutputStream
- import java.io.FileInputStream;
- /**
- * Created by fengkuirui on 2016/10/27.
- * 演示应用FileInputStream读取文件类的基本使用,对文件进行进行读取
- *
- */
- public class MyFileInputStream {
- /**
- * 显示读取文件中的内容,输出到控制台
- * @param path :文件的绝对路径加上文件名
- */
- public void ReadFile(String path){
- FileInputStream fis = null; //初始化文件流为空
- byte [] buffer = new byte[1024]; //读取缓存为1024个字节
- int n ;
- try{
- int i = 0;//记录读取的次数
- fis = new FileInputStream(path);
- while ((n = (fis.read(buffer))) != -1){//直至读取完毕后,结束此时 n = -1
- System.out.write(buffer,0,n);//将文件输出到控制台
- i++;//统计读取的次数
- System.out.println("=--------=");
- System.out.println(n);
- }
- }catch (Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(fis != null){
- fis.close();//关闭
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- MyFileInputStream mfis = new MyFileInputStream();
- mfis.ReadFile("E://read.txt");//送的为绝对路径
- }
- }
- import java.io.FileOutputStream;
- import java.io.PrintStream;
- /**
- * Created by fengkuirui on 2016/10/27.
- * 用FileOutputStream写入文件
- */
- public class MyFileOutputStream {
- /**
- * 将内容保存到文件
- * @param path :要保存的文件的绝对路径,包含文件名和后缀;
- *
- */
- public void WriteFile(String path){
- FileOutputStream fos = null;
- //声明一个PrintStream流
- PrintStream prints;
- try{
- fos = new FileOutputStream(path,true);//默认为覆盖内容的形式,如果设为true,为追加内容的方式
- prints = new PrintStream(fos);
- prints.println("世界这么大,我想去看看");
- prints.println("可是我没有时间啊");
- prints.close();
- System.out.println("写入文件完毕!");
- }catch (Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(fos != null){
- fos.flush();
- fos.close();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- MyFileOutputStream mfos = new MyFileOutputStream();
- mfos.WriteFile("E://write.txt");
- }
- }
3.Reader 和 Writer
- import java.io.BufferedReader;
- import java.io.FileReader;
- /**
- * Created by fengkuirui on 2016/10/27.
- * 利用字符流读取文件
- */
- public class MyReader {
- public void readFile(String path){
- FileReader fr = null;
- String str ;
- try{
- fr = new FileReader(path);
- BufferedReader buf = new BufferedReader(fr);//包装流
- str = new String();
- int i =0 ;
- while((str = buf.readLine()) != null){//每次只读一行
- System.out.println(str);
- System.out.println(i);
- i++;
- System.out.println("++++++++++++++");
- }
- }catch (Exception e){
- e.printStackTrace();
- }finally{
- try{
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- MyReader reader = new MyReader();
- reader.readFile("E://read.txt");
- }
- }
- import java.io.FileWriter;
- import java.io.PrintWriter;
- /**
- * Created by fengkuirui on 2016/10/27.
- * 字符流写入文件
- */
- public class MyWriter {
- /**
- *
- * @param path :要保存的文件的路径和名称加后缀
- */
- public void writeFile(String path){
- FileWriter fw = null;
- PrintWriter prints = null;
- try{
- fw = new FileWriter(path);
- prints = new PrintWriter(fw);//包装流;
- prints.println("我要学习Java,决不放弃!");
- prints.println("Never give up");
- }catch (Exception e){
- e.printStackTrace();
- }finally{
- if(prints != null){
- prints.flush();
- prints.close();
- }
- }
- }
- public static void main(String[] args) {
- MyWriter myw = new MyWriter();
- myw.writeFile("E://write.txt");
- MyReader myr = new MyReader();
- myr.readFile("E://write.txt");
- }
- }
4.BufferStream
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- /**
- * Created by fengkuirui on 2016/10/27.
- * 包装流到缓冲流
- * 提高读取速度
- */
- public class MyBufferStream {
- /**
- *
- * @param path :读取文件的路径
- */
- public void read(String path){
- File file = null;
- FileInputStream fis = null;
- BufferedInputStream bis = null;
- try{
- file = new File(path);//声明文件
- fis = new FileInputStream(file);//文件输入流
- bis = new BufferedInputStream(fis,1024);//设置缓存大小为1024字节
- byte[] data = new byte[(int)file.length()];
- while(bis.read(data) != -1){
- String str=new String(data);
- System.out.print(str);
- }
- }catch (Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(bis != null){
- bis.close();
- }
- if(fis != null){
- fis.close();
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- MyBufferStream mbs = new MyBufferStream();
- mbs.read("E://read.txt");
- }
- }
5.RandomAccessFile
- import java.io.File;
- import java.io.RandomAccessFile;
- /**
- * Created by fengkuirui on 2016/10/27.
- * 利用RandomAccessFile 进行文件的合并
- */
- public class MyRandomAccessFile {
- public void insert(String path1, String path2){
- File file1 = null;
- File file2 = null;
- RandomAccessFile raf1 = null;
- RandomAccessFile raf2 = null;
- try{
- file1 = new File(path1);
- file2 = new File(path2);
- raf1 = new RandomAccessFile(file1,"rw");
- raf2 = new RandomAccessFile(file2,"rw");
- byte[] buffer = new byte[1024];
- raf1.seek(raf1.length());//定位到最后,在最后添加;
- int n ;
- while((n=(raf2.read(buffer))) != -1){
- raf1.write(buffer,0,n);
- }
- raf1.close();
- raf2.close();
- } catch(Exception e){
- e.printStackTrace();
- }finally{
- try{
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) {
- MyRandomAccessFile mraf = new MyRandomAccessFile();
- mraf.insert("E://read.txt","E://write.txt");
- MyFileInputStream mfis = new MyFileInputStream();
- mfis.ReadFile("E://read.txt");
- }
- }
6.ByteArrayStream
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- /**
- * Created by fengkuirui on 2016/10/27.
- * ByteArrayInputStream and ByteArrayOutputStream ,
- * 直接将多个数据转化成字节数组
- */
- public class MyByteArrayStream {
- public void get(){
- int a = 1;
- int b = 12;
- int c = 123;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- baos.write(a);
- baos.write(b);
- baos.write(c);
- byte[] buffer = baos.toByteArray();
- System.out.println("将字节流转换为字节数组为:");
- for(byte i : buffer){
- System.out.println(i);
- }
- //将字节数组转换为字节流
- ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
- int bb;
- while((bb = bais.read()) != -1){
- System.out.println(bb);
- }
- }
- public static void main(String[] args) {
- MyByteArrayStream mbaos = new MyByteArrayStream();
- mbaos.get();
- }
- }
来源: