Java专题之IO

以下为我整理出来的JavaIO学习资料.大部门内容来源于rollenholt的博文《java中的IO整理》. (基本雷同) 非常感谢原博主.

另外对原文做了一些改进(我认为),并且附加上了我在学习过程中做的补充.


欣赏原博文的风格——以例子为主.因此我们先上几个例子.

【案例】创建一个新文件

package io;

import java.io.File;
import java.io.IOException;

public class CreateFile {

	public static void main(String[] args) {
		File file = new File("D:\\hello.txt");
		try {
			file.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(File.separator);
		System.out.println(File.pathSeparator);
		
		
		String fileName = "D:" + File.separator + "hell.txt";
		File f = new File(fileName);
		try {
			f.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

【运行结果】:

\

;

在d盘下会有一个名字为hello.txt 和 hell.txt的文件生成.

此处多说几句:有些同学可能认为,我直接在windows下使用\进行分割不行吗?当然是可以的。但是在linux下就不是\了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。


补充: 

File.separator 为单个文件路径内部的分隔符.如: D:\hello\hello.txt

File.pathSeparator 为多个文件路径之间的分隔符.如 D:\hello.txt;D:\hell.txt


【案例】删除一个文件

package io;

import java.io.File;

public class DeleteFile {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		if(f.exists()){
			f.delete();
		}else{
			throw new IllegalArgumentException("File: " +  fileName + " is not existed");
		}

	}

}

多说一句,此处抛出运行时异常,无需显式声明抛出或捕获,因此不会给客户端代码带来不便.绝大多数异常可概括为非法参数或非法状态,此处范范地抛出为非法参数异常.


【案例】创建一个文件夹

package io;

import java.io.File;

public class CreateFolder {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String fileName = "D:" + File.separator + "hello";
		File f = new File(fileName);
		f.mkdir();
		
		fileName = "D:" + File.separator + "hello" + File.separator + "parent" + File.separator + "child";
		f = new File(fileName);
		f.mkdirs(); 
	}

}


【运行结果】:

D盘下多了一个hello文件夹和一个hello\parent\child文件夹


mkdir() 与mkdirs()的区别. 

mkdirs()会创建包括任何必需且不存在的父目录,Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

mkdir()调用此方法,若必需的父目录不存在,则会抛出异常,


案例列出指定目录的全部文件(包括隐藏文件):

package io;

import java.io.File;

public class ListFiles {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String fileName = "D:";
		File f = new File(fileName);
		//获得文件名称
		for(String fn: f.list()){
			System.out.println(fn);
		}
		//获得文件完整名称(路径)
		for(File file : f.listFiles()){
			System.out.println(file.getPath());
		}
	}

}<strong>
</strong>
【运行结果】:


【案例】判断一个指定的路径是否为目录

package io;

import java.io.File;

public class JudgeDirectory {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		if(f.isDirectory()){
			System.out.println("YES");
		}else{
			System.out.println("NO");
		}
	}

}
【运行结果】:

NO

拓展一下:

不是文件夹就一定是文件? 不是的!

真实不存在的文件(在电脑里不存在对应文件的File对象)也可以判断类型.

package io;

import java.io.File;

public class FileOrFolder {

	public static void main(String[] args) {
		//existed file and folder
		File file1 = new File("D:" + File.separator + "hello");
		File file2 = new File("D:" + File.separator + "hello.txt");
		
		//inexistent file and folder
		File file3 = new File("D:" + File.separator + "hell");
		File file4 = new File("D:" + File.separator + "hell.txt");
		File file5 = new File("D:" + File.separator + "hell" + File.separator);
		
		isWhat(file1);
		isWhat(file2);
		isWhat(file3);
		isWhat(file4);
		isWhat(file5);

	}
	
	public static void isWhat(File file){
		if(file.isDirectory()){
			System.out.println("Folder");
		}else if(file.isFile()){
			System.out.println("File");
		}else{
			System.out.println("other");
		}
	}

}

【运行结果】:

Folder
File
other
File
other

【案例】搜索指定目录的全部内容

package io;

import java.io.File;

public class TraverseFolder {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator;
		File f = new File(fileName);
		print(f);
	}

	private static void print(File f) {
		// TODO Auto-generated method stub
		if(!f.exists())
			throw new IllegalArgumentException(f + " is not existed");
		
		if(f.isDirectory()){
			if(f.listFiles() != null){
				for(File childFile : f.listFiles()){
					print(childFile);
				}
			}
		}else{
			System.out.println(f);
		}
	}
	

}

【运行结果】:


到此稍微打住一下.说一些我觉得很有用的(可能并没什么用)的学习方法.只看干货的可以直接跳过.

学习IO,可以从以下几个方面入手:

1、熟悉IO相关类库类的API.

清楚都有哪些IO的相关类以及相应的API方法.可以通过一系列例子的学习来达到.进一步就要自己建立起IO类库结构网络.

2、使用正确的编程风格.

这一点体现在一众细节.包括异常应该在何时处理合适,包括需要关闭的对象如何创建,何时关闭,如何关闭,包括分隔符的可移植性等等.


学习过程中两样东西为你保驾护航,源码和API文档.如何查看源码和找到合适的API文档在这里就不详述了.让我们继续吧.


【案例】使用RandomAccessFile写入文件

package io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileWrite {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		try {
			RandomAccessFile raf = new RandomAccessFile(f, "rw"); //1
			raf.writeBytes("abcdefg");
			raf.writeInt(12);
			raf.writeBoolean(true);
			raf.writeChar('A');
			raf.writeFloat(1.21f);
			raf.writeDouble(12.123);
			raf.close(); //2
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

【运行结果】:

如果你此时打开hellotxt查看的话,会发现那是乱码。


这是一个不好的例子,也许大多数刚使用JavaIO,特别是对异常机制不太熟悉的同学就会写成这样.

我们来看一些存在哪些问题.在Java异常机制中,在try块中执行代码时,一旦产生异常,那么在产生异常的这条代码下的try块代码是不会执行的.也就是说,如果成功生成raf对象以后,并在close之前产生了异常时是不会执行close()方法的.

为了正确地关闭对象,我们做了如下修改:

package io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileWrite {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		RandomAccessFile raf = null; //1
		try {
			raf = new RandomAccessFile(f, "rw"); //2
			raf.writeBytes("abcdefg");
			raf.writeInt(12);
			raf.writeBoolean(true);
			raf.writeChar('A');
			raf.writeFloat(1.21f);
			raf.writeDouble(12.123);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(raf != null)
					raf.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

把关闭对象的代码放在finally块中

假象一下,假若我们同时需要关闭多个需要关闭的对象(Closeble对象),则会有如下代码:

finally{
			try {
				if(raf1 != null)
					raf1.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(raf2 != null)
					raf2.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(raf3 != null)
					raf3.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}//......more closeble need close
		}

有的读者也许会问,为什么不在一个try-catch块中关闭Closeble,前面已经说过,因为异常机制,若在关闭raf1时出现异常,那么是不会执行关闭raf2和raf3的代码的.

为了更加方便地关闭Closeble,我们提取出来了一个辅助静态方法,把它放在工具类中:

package io;

import java.io.Closeable;
import java.io.IOException;

public class IOUtil {
	
	public static void close(Closeable c){
		try {
			if(c != null){
				c.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

最后改写的代码为:

package io;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileWrite {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		RandomAccessFile raf = null; //1
		try {
			raf = new RandomAccessFile(f, "rw"); //2
			raf.writeBytes("abcdefg");
			raf.writeInt(12);
			raf.writeBoolean(true);
			raf.writeChar('A');
			raf.writeFloat(1.21f);
			raf.writeDouble(12.123);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(raf); //3
		}
	}

}

在接下来的案例中关闭Closeble,都将使用工具类进行关闭.


字节流

【案例】向文件中写入字符串

package io;

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

public class ByteStreamWrite {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		
		OutputStream os = null;
		try {
			os = new FileOutputStream(f);
			String str = "你好";
			byte[] bytes = str.getBytes();
			
			//一起写
			os.write(bytes);
			
			str = " 理解万岁!";
			bytes = str.getBytes();
			//一个一个字节写
			for(int i=0; i<bytes.length; i++){
				os.write(bytes[i]);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(os);
		}
		
		
		
	}

}

【运行结果】:

查看hello.txt会看到“你好 理解万岁”


【案例】向文件中追加新内容

package io;

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

public class AddToFile {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		OutputStream out = null;
		try {
			out = new FileOutputStream(f,true);
			String appendContent = " 这是追加上来的内容.";
			byte[] bytes = appendContent.getBytes();
			out.write(bytes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(out);
		}
	}

}

【运行结果】:

查看hello.txt会看到“你好 理解万岁 这是追加上来的内容”


【案例】读取文件内容

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ByteStreamRead {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		InputStream in = null;
		try {
			in = new FileInputStream(f);
			byte[] bytes = new byte[1024];
			
			in.read(bytes);
			String content = new String(bytes);
			System.out.println("读入内容为: " + content);
			System.out.println("读入字符串长度为: " + content.length());//有大量空格
			in.close();
			
			in = new FileInputStream(f);
			bytes = new byte[1024];
			int len = in.read(bytes);
			content = new String(bytes, 0, len); //利用read(bytes)的返回值
			System.out.println("读入长度为: " + len);
			System.out.println("读入内容为: " + content);
			System.out.println("读入字符串长度为: " + content.length());//没有多余的空格
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(in);
		}

	}

}
【运行结果】:

读入内容为: 你好 理解万岁 这是追加上来的内容.

读入字符串长度为: 1009
读入长度为: 33
读入内容为: 你好 理解万岁 这是追加上来的内容.
读入字符串长度为: 18


读者观察上面的例子可以看出,我们预先申请了一个指定大小的空间,但是有时候这个空间可能太小,有时候可能太大,我们需要准确的大小,这样节省空间,那么我们可以这样干:

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ByteStreamReadPrecise {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
        File f = new File(fileName);
        InputStream in = null;
        
		try {
			 in = new FileInputStream(f);
			 byte[] buffer = new byte[(int)f.length()];   //file must be small
			 in.read(buffer);
			 System.out.println("文件长度为: " + f.length());
			 System.out.println(new String(buffer));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(in);
		}
        
	}

}
【运行结果】:

文件长度为: 33
你好 理解万岁 这是追加上来的内容.


补充:局限于小于或等于int最大值byte数的文件.


细心的读者可能会发现,上面的几个例子都是在知道文件的内容多大,然后才展开的,有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ByteStreamReadUnkownLength {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
        File f = new File(fileName);
        InputStream in = null;
		try {
			  in = new FileInputStream(f);
			 byte[] buffer = new byte[1024];   //file must be small(less than 1024bytes)
			 int count = 0;
			 int temp = 0;
			 while( (temp=in.read()) != -1){
				 buffer[count++] = (byte)temp;
			 }
			 String content = new String(buffer);
			 System.out.println(content.trim()); //string.trim()可去除多余的空格
			 System.out.println(content.trim().length());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(in);
		}

	}

}
【运行结果】:

你好 理解万岁 这是追加上来的内容.
18

提醒一下,当独到文件末尾的时候会返回-1.正常情况下是不会返回-1


字符流

【案例】向文件中写入数据

package io;

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

public class CharacterStreamWrite {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Writer out = null;
		try {
			out = new FileWriter(f);
			String str = "hello";
			out.write(str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(out);
		}
	}

}

【运行结果】:

当你打开hellotxt的时候,会看到hello

其实这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。

当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:

Writer out =new FileWriter(f,true);

这样,当你运行程序的时候,会发现文件内容变为:

hellohello如果想在文件中换行的话,需要使用“\r\n

比如将str变为String str="\r\nhello";

这样文件追加的str的内容就会换行了。

【案例】从文件中读取内容

package io;

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

public class CharacterStreamRead {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		char[] ch = new char[100];
		Reader read = null;
		try {
			read = new FileReader(f);
			int count = read.read(ch);
			System.out.println(new String(ch,0,count));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(read);
		}
	}

}

【运行结果】:

hello


当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。

package io;

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

public class CharacterStreamReadLoop {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		char[] buff = new char[100];
		Reader read = null;
		try {
			read = new FileReader(f);
			int temp = 0;
			int count = 0;
			while((temp=read.read()) != -1){
				buff[count++] = (char)temp;
			}
			System.out.println(new String(buff, 0, count));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(read);
		}
	}

}
【运行结果】:

hello


关于字节流和字符流的区别

实际上字节流在操作的时候本身是不会用到缓冲区的,是文件本身的直接操作的,但是字符流在操作的 时候下后是会用到缓冲区的,是通过缓冲区来操作文件的。

读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。

使用字节流好还是字符流好呢?

答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。


文件复制


下面我们使用程序来复制文件吧。

基本思路还是从一个文件中读入内容,边读边写入另一个文件,就是这么简单。

首先编写下面的代码:

【案例】复制文件

package io;

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

public class CopyFile {

	public static void main(String[] args) {
		String filePath = "D:" + File.separator + "hello.txt";
		String targetPath = "D:" + File.separator + "hello_copy.txt";
		copy(filePath, targetPath);

	}
	
	public static void copy(String sourcePath, String targetPath){
		File sourceFile = new File(sourcePath);
		File targetFile = new File(targetPath);
		
		if(!sourceFile.exists())
			throw new IllegalArgumentException("source file : " + sourceFile + " is not existed");
		if(targetFile.exists())
			throw new IllegalArgumentException("target file : " + sourceFile + " is already existed");
			
		InputStream input = null;
		OutputStream out = null;
		try {
			input = new FileInputStream(sourceFile);
			out = new FileOutputStream(targetFile);
			int temp = 0;
			while((temp=input.read()) != -1){
				out.write(temp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(out);
			IOUtil.close(input);
		}
	}

}
【运行结果】:

D盘多出文件——hello_copy.txt


OutputStreramWriter 和InputStreamReader类

整个IO类中除了字节流和字符流还包括字节和字符转换流。

OutputStreramWriter将输出的字符流转化为字节流

InputStreamReader将输入的字节流转换为字符流

但是不管如何操作,最后都是以字节的形式保存在文件中的。


【案例】将字节输出流转化为字符输出流

package io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class ByteOutputStreamToCharacterOutputStream {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Writer out = null;
		try {
			out = new OutputStreamWriter(new FileOutputStream(f));
			out.write("hello");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(out);
		}
	}

}


【运行结果】:

文件中内容为:hello

【案例】将字节输入流变成字符输入流

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class ByteInputStreamToCharacterInputStream {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Reader read = null;
		try {
			read = new InputStreamReader(new FileInputStream(f));
			char[] buff = new char[100];
			int len = read.read(buff);
			System.out.println(new String(buff, 0, len));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(read);
		}

	}

}

【运行结果】:

hello


前面列举的输出输入都是以文件进行的,现在我们以内容为输出输入目的地,使用内存操作流

ByteArrayInputStream 主要将内容写入内容

ByteArrayOutputStream  主要将内容从内存输出


【案例】使用内存操作流将一个大写字母转化为小写字母

package io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class WriteMemoryToMemory {

	public static void main(String[] args) {
		String str = "SHAOCHENGCHENG";
		ByteArrayInputStream input = new ByteArrayInputStream(str.getBytes());
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		int temp = 0;
		while((temp=input.read()) != -1){
/*			char ch = (char)temp;
			output.write(Character.toLowerCase(ch));*/
			output.write(Character.toLowerCase(temp));
		}
		String outStr = output.toString();
		IOUtil.close(output);
		IOUtil.close(input);
		
		System.out.println(outStr);

	}

}


【运行结果】:

shaochengcheng


内容操作流一般使用来生成一些临时信息采用的,这样可以避免删除的麻烦。


管道流

管道流主要可以进行两个线程之间的通信。

PipedOutputStream 管道输出流

PipedInputStream 管道输入流


【案例】验证管道流

package io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class ChannelStream {
	private static class Send implements Runnable{
		private PipedOutputStream out;
		
		public Send() {
			out = new PipedOutputStream();
		}
		
		public PipedOutputStream getOut(){
			return this.out;
		}
		
		@Override
		public void run() {
			String message = "hello, Shao";
			try {
				out.write(message.getBytes());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				IOUtil.close(out);
			}
			
		}
		
	}
	
	private static class Recive implements Runnable{
		private PipedInputStream input;
		
		public Recive() {
			this.input = new PipedInputStream();
		}
		
		public PipedInputStream getInput(){
			return this.input;
		}
		
		@Override
		public void run() {
			byte[] buff = new byte[1000];
			int len = 0;
			try {
				len = this.input.read(buff);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				IOUtil.close(input);
			}
			System.out.println("接受的内容为 " + new String(buff, 0, len));
			
		}
		
	}
	
	public static void main(String[] args) {
		Send send = new Send();
		Recive recive = new Recive();
		
		try {
			send.getOut().connect(recive.getInput());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		new Thread(send).start();
		new Thread(recive).start();

	}

}
【运行结果】:

接受的内容为 hello, Shao


【案例】打印流

package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class PrintStreamPure {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File file = new File(fileName);
		OutputStream output;
		PrintStream print = null;
		try {
			output = new FileOutputStream(file);
			print = new PrintStream(output);
			print.println(true);
			print.println("Shao");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(print);
		}
		
		

	}

}

【运行结果】:

hello.txt内容为:

true

Shao


细心的读者会发现,这里有两个Closeble(output 和 print) 为什么只关闭可一个呢?

查看源码就会发现,new PrintStream(new FileOutputStream(file)) 这样的嵌套Closeble对象中的close()方法已经调用了被嵌套的Closeble对象(FileOutputStream)的close()方法.形成了一个close()调用链.

因此只需要调用最外层的close()方法就行.


当然也可以格式化输出


package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class PrintStreamFormat {

	public static void main(String[] args) {
		String fileName = "D:" + File.separator + "hello.txt";
		File file = new File(fileName);
		OutputStream output = null;
		PrintStream print = null;
		try {
			output = new FileOutputStream(file);
			print = new PrintStream(output);
			String name = "Shao";
			int age = 20;
			print.printf("姓名:%s.年龄:%d.", name, age);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(print);
		}
		
		

	}

}
【运行结果】:

hello.txt内容为:

姓名:Shao.年龄:20.


【案例】使用OutputStream向屏幕上输出内容

package io;

import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamToScreen {

	public static void main(String[] args) {
		OutputStream out = System.out;
		try {
			out.write("hello".getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//因为是System.out,保存在System里,将来程序极有可能需要用到,因此不关闭
	}

}

【运行结果】:

hello


【案例】输出重定向

package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class RedirectOutput {

	public static void main(String[] args) {
		System.out.println("hello");
		File file = new File("D:" + File.separator + "hello.txt");
		PrintStream ps = null;
		try {
			ps = new PrintStream(new FileOutputStream(file));
			System.setOut(ps);
			System.out.println("在文件中看到.");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(ps);
		}
		
	}

}

 【运行结果】: 

控制台:hello

hello.txt内容为:在文件中看到.

【案例】输入重定向

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class RedirectInput {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		InputStream is = null;
		if(!file.exists())
			throw new IllegalArgumentException(file + " is not existed");
		try {
			is = new FileInputStream(file);
			System.setIn(is);
			
			byte[] buff = new byte[1024];
			int len = 0;
			len = System.in.read(buff);
			System.out.println(new String(buff, 0 , len));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(is);
		}
		
		
	}

}

【运行结果】:

在文件中看到.


BufferedReader的小例子

【案例】使用缓冲区从键盘上读入内容

注意: BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流

package io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class BufferedRead {

	public static void main(String[] args) {
		Reader reader = new InputStreamReader(System.in);
		BufferedReader buffReader = new BufferedReader(reader);
		String str = null;
		System.out.println("请输入内容");
		try {
			str = buffReader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(buffReader);
		}
		
		System.out.println("你输入的内容是: " + str);
	}

}

【运行结果】:

(我的是)

请输入内容
halo
你输入的内容是: halo


Scanner类


【案例】Scanner从键盘读数据

package io;

import java.util.Scanner;

public class ScannerReadKeyBoard {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int temp = scanner.nextInt();
		System.out.println(temp);
		
		float f = scanner.nextFloat();
		System.out.println(f);
		
		scanner.close();
		
	}

}
【运行结果】:


【案例】Scanner从文件中读出内容


package io;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerReadFile {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		Scanner scanner = null;
		try {
			scanner = new Scanner(file);
			String str = scanner.next();
			System.out.println("从文件中读取的内容是: " + str);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(scanner);
		}
	}

}
【运行结果】:


数据操作流DataOutputStream、DataInputStream类

【案例】DataOutputStream写入文件

package io;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataStreamWrite {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		char[] buff = {'A', 'B', 'C'};
		DataOutputStream out = null;
		try {
			out = new DataOutputStream(new FileOutputStream(file));
			for(char c : buff){
				out.writeChar(c);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(out);
		}
		
		

	}

}

【运行结果】:

hello.txt文件中内容为: A B C


现在我们在上面例子的基础上,使用DataInputStream读出内容


package io;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class DataStreamRead {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		DataInputStream input = null;
		try {
			input = new DataInputStream(new FileInputStream(file));
			char[] ch = new char[10];
			int count = 0;
			char temp;
			while((temp=input.readChar()) != 'C'){
				ch[count++] = temp;
			}
			System.out.println(ch);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(input);
		}

	}

}
【运行结果】:

AB


合并流 SequenceInputStream

SequenceInputStream主要用来将2个流合并在一起,比如将两个txt中的内容合并为另外一个txt。下面给出一个实例:

【案例】

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;

public class SequenceInputStreamDemo {

	public static void main(String[] args) {
		File file1 = new File("D:" + File.separator + "hello1.txt" );
		File file2 = new File("D:" + File.separator + "hello2.txt" );
		File file3 = new File("D:" + File.separator + "hello.txt" );
		
		OutputStream output = null;
		SequenceInputStream sis = null;
		try {
			output = new FileOutputStream(file3);

			@SuppressWarnings("resource") //sis will close the stream
			InputStream input2 = new FileInputStream(file2);
			sis = new SequenceInputStream(new FileInputStream(file1), input2);
			
			int temp = 0;
			while((temp=sis.read()) != -1){
				output.write(temp);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(sis);
			IOUtil.close(output);
		}
		
		
		
		
	}

}
【运行结果】:

结果会在hello.txt文件中包含hello1.txthello2.txt文件中的内容。


文件压缩 ZipOutputStream类


【案例】压缩单文件

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		File zipFile = new File("D:" + File.separator + "hello.zip");
		
		InputStream input = null;
		ZipOutputStream zipOut = null;
		
		try {
			input = new FileInputStream(file);
			
			zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
			
			zipOut.putNextEntry(new ZipEntry(file.getName()));
			
			zipOut.setComment("comment");
			
			int temp = 0;
			while((temp=input.read()) != -1){
				zipOut.write(temp);
			}
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(input);
			IOUtil.close(zipOut);
		}
	}

}

【运行结果】:



【案例】压缩多文件

在这之前我们首先建立一个稍微丰富一些的文件夹:


这个文件夹有这么些东西:空文件夹(empty)、非空文件夹(folder)、文件(hello.txt)

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipOutputStreamMutiDemo {

	public static void main(String[] args) {
		//要被压缩的文件夹
		File file = new File("D:" + File.separator + "hello");
		File zipFile = new File("D:" + File.separator + "zipFile.zip");
		
		ZipOutputStream zipOut = null;
		
		try {
			zipOut = new ZipOutputStream(new FileOutputStream(zipFile),Charset.forName("gbk"));
			
			zipOut.setComment("这是一个文件夹的压缩文件");
			
			compress(file, zipOut, "");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(zipOut);
		}
		
	}

	private static void compress(File file, ZipOutputStream zipOut, String base) throws IOException{
		if(file.isDirectory()){
			File[] childFiles = file.listFiles();
			if(childFiles.length > 0){
				for(File f : childFiles){
					compress(f, zipOut, base + file.getName() + File.separator);
				}
			}else{
				//压缩空的文件夹
				zipOut.putNextEntry(new ZipEntry(base + file.getName() + File.separator));
				zipOut.closeEntry();
			}
			
		}else if(file.isFile()){
			InputStream input = new FileInputStream(file);
			zipOut.putNextEntry(new ZipEntry(base + file.getName()));
			byte[] buff = new byte[1024];
			int len = 0;
			while((len=input.read(buff)) != -1){
				zipOut.write(buff, 0, len);
			}
			zipOut.closeEntry();
			IOUtil.close(input);
		}
		
	}

}

【运行结果】:



不过这里碰到了一个未解决的问题.就是在压缩空文件夹时会产生一个大小为0,名字为空的文件在zip文件中.不过解压之后并没有看到这个文件.(也算是不影响了)




大家自然想到,既然能压缩,自然能解压缩,在谈解压缩之前,我们会用到一个ZipFile类,先给一个这个例子吧。java中的每一个压缩文件都是可以使用ZipFile来进行表示的


【案例】解压只含一个文件的zip文件

package io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class DecompressZipDemo {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.zip");
		File outFile = new File("D:" + File.separator + "unZipFile.txt");
		
		InputStream input = null;
		OutputStream output = null;
		ZipFile zipFile = null;
		
		try {
			zipFile = new ZipFile(file);
			ZipEntry entry = zipFile.getEntry("hello.txt");
			
			input = zipFile.getInputStream(entry);
			output = new FileOutputStream(outFile);
			
			int temp = 0;
			while((temp=input.read()) != -1){
				output.write(temp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(input);
			IOUtil.close(output);
			IOUtil.close(zipFile);			
		}
		

	}

}
【运行结果】:


【案例】解压多个文件

(相比原博文少用到了一个类ZipInputStream),可参考原博文

package io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class DecompressZipMuti {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "zipFile.zip");
		String base = "D:" + File.separator;
		
		File outFile = null;
		ZipFile zipFile = null;
		InputStream input = null;
		OutputStream output = null;
		
		try {
			zipFile = new ZipFile(file);
			Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
			while(enumeration.hasMoreElements()){
				ZipEntry entry = enumeration.nextElement();
				System.out.println("解压缩 " + entry.getName() + " 文件");
				outFile = new File(base + entry.getName());
				//判断是否是文件夹,如果是文件夹,则创建文件夹
				if(entry.getName().endsWith(File.separator)){
					outFile.mkdirs();
				}else{
					if(!outFile.getParentFile().exists()){
						outFile.getParentFile().mkdirs();
					}
					if(!outFile.exists()){
						input = zipFile.getInputStream(entry);
						output = new FileOutputStream(outFile);
						int temp = 0;
						while((temp=input.read()) != -1){
							output.write(temp);
						}
						IOUtil.close(input);
						IOUtil.close(output);
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(zipFile);
		}
	}

}
【运行结果】:


PushBackInputStream回退流

【案例】回退流操作

package io;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

public class PushBackInputStreamDemo {

	public static void main(String[] args) {
		String str = "hello,shao";
		PushbackInputStream pushInput = null;
		
		pushInput = new PushbackInputStream(new ByteArrayInputStream(str.getBytes()));
		
		int temp = 0;
		try {
			while((temp=pushInput.read()) != -1){
				if(temp == ','){
					//回退
					pushInput.unread(temp);
					//重新读出来
					temp = pushInput.read();
					System.out.print("(回退" + (char)temp + ")");
				}else{
					System.out.print((char)temp);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(pushInput);
		}
	}

}
【运行结果】:

hello(回退,)shao


编码问题


package io;

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

public class CharSetDemo {

	public static void main(String[] args) {
		System.out.println("系统默认编码为: " + System.getProperty("file.encoding"));
		
		//乱码的产生
		File file = new File("D:" + File.separator + "hello.txt");
		OutputStream out = null;
		try {
			 out = new FileOutputStream(file);
			 byte[] bytes = "你好".getBytes("ISO8859-1");
			 out.write(bytes);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(out);
		}
	}

}

一般情况下产生乱码,都是由于编码不一致的问题。


对象的序列化


对象序列化就是把一个对象变为二进制数据流的一种方法。


一个类要想被序列化,就行必须实现java.io.Serializable接口。虽然这个接口中没有任何方法,就如同之前的cloneable接口一样。实现了这个接口之后,就表示这个类具有被序列化的能力。


先让我们实现一个具有序列化能力的类吧:

import java.io.*;
/**
 * 实现具有序列化能力的类
 * */
public class SerializableDemo implements Serializable{
    public SerializableDemo(){
         
    }
    public SerializableDemo(String name, int age){
        this.name=name;
        this.age=age;
    }
    @Override
    public String toString(){
        return "姓名:"+name+"  年龄:"+age;
    }
    private String name;
    private int age;
}

这个类就具有实现序列化能力


在继续将序列化之前,先将一下ObjectInputStream和ObjectOutputStream这两个类


【案例】ObjectOutputStream写对象

package io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectOutputStreamDemo {
	@SuppressWarnings("serial") // because simple class
	public static class Person implements Serializable{
		private String name;
		private int age;
		
		public Person(){
			
		}
		
		public Person(String name, int age){
			this.name = name;
			this.age = age;
		}
		
		@Override
		public String toString() {
			return "Person [name=" + name + ", age=" + age + "]";
		}
	}
	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(new Person("Shao", 20));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(oos);
		}

	}

}
【运行结果】:
当我们查看产生的hello.txt的时候,看到的是乱码,呵呵。因为是二进制文件。
虽然我们不能直接查看里面的内容,但是我们可以使用ObjectInputStream类查看:

【案例】ObjectInputStream读对象

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamDemo {

	public static void main(String[] args) {
		File file = new File("D:" + File.separator + "hello.txt");
		ObjectInputStream input = null;
		try {
			 input = new ObjectInputStream(new FileInputStream(file));
			 Object obj = input.readObject();
			 System.out.println(obj);
		} catch (IOException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(input);
		}

	}

}
【运行结果】:

Person [name=Shao, age=20]

到底序列化什么内容呢?
其实只有属性会被序列化。


Externalizable接口


被Serializable接口声明的类的对象的属性都将被序列化,但是如果想自定义序列化的内容的时候,就需要实现Externalizable接口。


当一个类要使用Externalizable这个接口的时候,这个类中必须要有一个无参的构造函数,如果没有的话,在构造的时候会产生异常,这是因为在反序列话的时候会默认调用无参的构造函数。


现在我们来演示一下序列化和反序列话:


package io;

import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ExternaliableDemo {
	

	public static void main(String[] args) {
		ser();
		dser();

	}
	
	public static void ser(){
		File file = new File("D:" + File.separator + "hello.txt");
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(new Person("Shao", 20, 1));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(oos);
		}
	}
	
	public static void dser(){
		File file = new File("D:" + File.separator + "hello.txt");
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(file));
			Object object = ois.readObject();
			System.out.println(object);
		} catch (IOException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			IOUtil.close(ois);
		}
	}

}

class Person implements Externalizable{
	private String name;
	private int age;
	private int level;
	
	public Person(){
		
	}
	
	public Person(String name, int age, int level) {
		super();
		this.name = name;
		this.age = age;
		this.level = level;
	}

	//复写这个方法,根据需要进行序列化
	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		//序列化与反序列读写的数据有对应顺序.
		out.writeObject(this.name);
		out.writeInt(this.level);
		out.writeInt(this.age);
	}
	
	//复写这个方法,根据需要进行反序列化
	@Override
	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		this.name = (String)in.readObject();
		this.level = in.readInt();
		
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", level=" + level + "]";
	}


	
	
}
【运行结果】:

Person [name=Shao, age=0, level=1]

Serializable接口实现的操作其实是吧一个对象中的全部属性进行序列化,当然也可以使用我们上使用是Externalizable接口以实现部分属性的序列化,但是这样的操作比较麻烦,


当我们使用Serializable接口实现序列化操作的时候,如果一个对象的某一个属性不想被序列化保存下来,那么我们可以使用transient关键字进行说明


同样写在最后:本文章没有涉及java.nio(new io ),有时间会补上. 奉上一篇总结JavaIO结构的博文.《Java中IO结构图》

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值