`
dengqsintyt
  • 浏览: 288469 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

Java IO操作

阅读更多

其实本打算先写一下java 新IO呢,但是为了区分概念,还是先整理下Java IO操作,以例子为主。

1.创建新文件

 

public static void createFile(){
		File f=new File("c:\\test.txt");
        try{
            f.createNewFile();
        }catch (Exception e) {
            e.printStackTrace();
        }
	}

  运行结果:在c盘下会有一个名字为test.txt的文件

 

 

2.File类的两个常量

 

public static void FileConstant(){
	System.out.println(File.separator);
        System.out.println(File.pathSeparator);
	}

 

运行结果:

 \

;

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

 

3.删除一个文件

 

public static void deleteFile(){
		 String fileName="c:"+File.separator+"test.txt";
	        File f=new File(fileName);
	        if(f.exists()){
	            f.delete();
	        }else{
	            System.out.println("文件不存在");
	        }
	}

 

 

4.创建一个文件夹

 

public static void createDir(){
		String fileName="D:"+File.separator+"hello";
        File f=new File(fileName);
        f.mkdir();
	}

 

 

5.列出指定目录的全部文件(包括隐藏文件)

 

//使用FileList,输出是全路径
public static void ListFileFromDir(){
		String fileName="D:"+File.separator;
        File f=new File(fileName);
        String[] str=f.list();
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
	}

 或者

 

 

//使用FileList,输出是全路径
	public static void ListFileFromDir1(){
		String fileName="D:"+File.separator;
        File f=new File(fileName);
        File[] str=f.listFiles();
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }

	}

 

 

6.搜索指定目录的全部内容

 

public static void print(File f){
        if(f!=null){
            if(f.isDirectory()){
                File[] fileArray=f.listFiles();
                if(fileArray!=null){
                    for (int i = 0; i < fileArray.length; i++) {
                        //递归调用
                        print(fileArray[i]);
                    }
                }
            }
            else{
                System.out.println(f);
            }
        }
    }

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

 

 

6.使用RandomAccessFile写入文件

 

public static void WriteFileUseRandomAccessFile() throws IOException{
	    String fileName="D:"+File.separator+"hello.txt";
	    File f=new File(fileName);
	    RandomAccessFile demo=new RandomAccessFile(f,"rw");
	    demo.writeBytes("asdsad");
	    demo.writeInt(12);
	    demo.writeBoolean(true);
	    demo.writeChar('A');
	    demo.writeFloat(1.21f);
	    demo.writeDouble(12.123);
	    demo.close();
	}

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

 

 

7.字节流

向文件中写入字符串

/**
	 * 字节流
	 * 向文件中写入字符串
	 * */
	public static void writeOutputStream()throws IOException{
	String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        OutputStream out =new FileOutputStream(f);
        String str="你好";
        byte[] b=str.getBytes();
        out.write(b);
        out.close();
	}

 

 

8.字节流,向文件中一个字节一个字节的写入字符串

/**
	 * 字节流
	 * 向文件中写入字符串
	 * */
	public static void writeOutputStream1()throws IOException{
		String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        OutputStream out =new FileOutputStream(f);
        String str="你好";
        byte[] b=str.getBytes();
        out.write(b);
        out.close();
	}

  

9.向文件中追加新内容

 

/**
	     * 字节流
	     * 向文件中追加新内容:
	     * */
	    public static void appContentFromFile() throws IOException {
	    	String fileName="D:"+File.separator+"hello.txt";
	        File f=new File(fileName);
	        OutputStream out =new FileOutputStream(f,true);
	        String str="hehe";
	        //String str="\r\nRollen";  可以换行
	        byte[] b=str.getBytes();
	        for (int i = 0; i < b.length; i++) {
	            out.write(b[i]);
	        }
	        out.close();
	    }
 

 

 10.读取文件内容

 

/**
	 * 字节流
	 * 读文件内容
	 * */
	public static void readContentFromFile()throws IOException{
		String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        InputStream in=new FileInputStream(f);
        byte[] b=new byte[1024];
        in.read(b);
        in.close();
        System.out.println(new String(b));
	}
 

 

11.上面的这个例子读取出来会有大量的空格,我们可以利用in.read(b);的返回值来设计程序。如下:

 

/**
	 * 字节流 读文件内容
	 */
	public static void readContentFromFile1() throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		InputStream in = new FileInputStream(f);
		byte[] b = new byte[1024];
		int len = in.read(b);
		in.close();
		System.out.println("读入长度为:" + len);
		System.out.println(new String(b, 0, len));
	}
 

 

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

 

/**
	 * 字节流
	 * 读文件内容,节省空间
	 * */
	public static void readContentFromFile2() throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		InputStream in = new FileInputStream(f);
		byte[] b = new byte[(int) f.length()];
		in.read(b);
		System.out.println("文件长度为:" + f.length());
		in.close();
		System.out.println(new String(b));
	}
 

 

13.将上面的例子改为一个一个读:

 

/**
	 * 字节流 读文件内容,节省空间
	 */
	public static void readContentFromFile3() throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		InputStream in = new FileInputStream(f);
		byte[] b = new byte[(int) f.length()];
		for (int i = 0; i < b.length; i++) {
			b[i] = (byte) in.read();
		}
		in.close();
		System.out.println(new String(b));
	}
 

 

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

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

 

 

 

/**
	 * 字节流 读文件
	 */
	public static void readContentFromFile4() throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		InputStream in = new FileInputStream(f);
		byte[] b = new byte[1024];
		int count = 0;
		int temp = 0;
		while ((temp = in.read()) != (-1)) {
			b[count++] = (byte) temp;
		}
		in.close();
		System.out.println(new String(b));
	}
 

 

 

 15.字符流

     向文件中写入数据

 

/**
	 * 字符流
	 * 写入数据
	 * */
	public static void writeContentFromFile() throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Writer out = new FileWriter(f);
		String str = "hello";
		out.write(str);
		out.close();
	}
 当你打开hello。txt的时候,会看到hello

 

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

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

Writer out =new FileWriter(f,true);

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

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

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

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

 

16.从文件中读内容

    

 

/**
	 * 字符流
	 * 从文件中读出内容
	 * */
	public static void writeContentFromFile1() throws IOException {
	        String fileName="D:"+File.separator+"hello.txt";
	        File f=new File(fileName);
	        char[] ch=new char[100];
	        Reader read=new FileReader(f);
	        int count=read.read(ch);
	        read.close();
	        System.out.println("读入的长度为:"+count);
	        System.out.println("内容为"+new String(ch,0,count));
	}
 

 

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

 

/**
	 * 字符流 从文件中读出内容
	 */
	public static void writeContentFromFile2() throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		char[] ch = new char[100];
		Reader read = new FileReader(f);
		int temp = 0;
		int count = 0;
		while ((temp = read.read()) != (-1)) {
			ch[count++] = (char) temp;
		}
		read.close();
		System.out.println("内容为" + new String(ch, 0, count));
	}
    关于字节流和字符流的区别

 

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

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

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

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

 

18.文件的复制

 

/**
	 * 文件的复制
	 */
	public static void copyFile(String[] args) throws IOException {
		if (args.length != 2) {
			System.out.println("命令行参数输入有误,请检查");
			System.exit(1);
		}
		File file1 = new File(args[0]);
		File file2 = new File(args[1]);

		if (!file1.exists()) {
			System.out.println("被复制的文件不存在");
			System.exit(1);
		}
		InputStream input = new FileInputStream(file1);
		OutputStream output = new FileOutputStream(file2);
		if ((input != null) && (output != null)) {
			int temp = 0;
			while ((temp = input.read()) != (-1)) {
				output.write(temp);
			}
		}
		input.close();
		output.close();
	}

 然后在命令行下面

  javac hello.java

  java hello d:\hello.txt d:\rollen.txt

现在你就会在d盘看到rollen.txt了

 

19.将字节输出流转化为字符输出流

 

OutputStreramWriter InputStreamReader

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

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

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

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

 

/**
	 * 将字节输出流转化为字符输出流
	 */
	public static void fromByteToChar() throws IOException {
		String fileName = "d:" + File.separator + "hello.txt";
		File file = new File(fileName);
		Writer out = new OutputStreamWriter(new FileOutputStream(file));
		out.write("hello");
		out.close();
	}

 

20.将字节输入流变为字符输入流

/**
	 * 将字节输入流变为字符输入流
	 */
	public static void fromByteToChar1() throws IOException {
		String fileName = "d:" + File.separator + "hello.txt";
		File file = new File(fileName);
		Reader read = new InputStreamReader(new FileInputStream(file));
		char[] b = new char[100];
		int len = read.read(b);
		System.out.println(new String(b, 0, len));
		read.close();
	}

 

21.使用内存操作流将一个大写字母转化为小写字母

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

  ByteArrayInputStream 主要将内容写入内容

  ByteArrayOutputStream  主要将内容从内存输出

/**
	 * 使用内存操作流将一个大写字母转化为小写字母
	 */
	public static void fromByteToChar2() throws IOException {
		String str = "ROLLENHOLT";
		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));
		}
		String outStr = output.toString();
		input.close();
		output.close();
		System.out.println(outStr);
	}

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

 

22.管道流

 

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

     PipedOutputStream 管道输出流

   PipedInputStream 管道输入流
import java.io.*;

/**
 * 验证管道流
 * */

/**
 * 消息发送类
 */
class Send implements Runnable {
	private PipedOutputStream out = null;

	public Send() {
		out = new PipedOutputStream();
	}

	public PipedOutputStream getOut() {
		return this.out;
	}

	public void run() {
		String message = "hello , Rollen";
		try {
			out.write(message.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

/**
 * 接受消息类
 */
class Recive implements Runnable {
	private PipedInputStream input = null;

	public Recive() {
		this.input = new PipedInputStream();
	}

	public PipedInputStream getInput() {
		return this.input;
	}

	public void run() {
		byte[] b = new byte[1000];
		int len = 0;
		try {
			len = this.input.read(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("接受的内容为 " + (new String(b, 0, len)));
	}
}

/**
 * 测试类
 */
class hello {
	public static void main(String[] args) throws IOException {
		Send send = new Send();
		Recive recive = new Recive();
		try {
			// 管道连接
			send.getOut().connect(recive.getInput());
		} catch (Exception e) {
			e.printStackTrace();
		}
		new Thread(send).start();
		new Thread(recive).start();
	}
}
 
23.打印流
/**
	 * 使用PrintStream进行输出
	 */
	public static void printStream1() throws IOException {
		PrintStream print = new PrintStream(new FileOutputStream(new File("d:"
				+ File.separator + "hello.txt")));
		print.println(true);
		print.println("Rollen");
		print.close();
	}
 
24.BufferedReader
注意: BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
 
/**
	 * 使用缓冲区从键盘上读入内容
	 */
	public static void bufferedReader() throws IOException{
		BufferedReader buf = new BufferedReader(
				new InputStreamReader(System.in));
		String str = null;
		System.out.println("请输入内容");
		try {
			str = buf.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("你输入的内容是:" + str);
	}
 
25.Scanner

 

其实我们比较常用的是采用Scanner类来进行数据输入,下面来给一个Scanner的例子吧

 

/**
	 * Scanner的小例子,从文件中读内容
	 */
	public static void scanner() throws IOException {
		File file = new File("d:" + File.separator + "hello.txt");
		Scanner sca = null;
		try {
			sca = new Scanner(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		String str = sca.next();
		System.out.println("从文件中读取的内容是:" + str);
	}

 

26.合并流 SequenceInputStream

 

 

/**
	 * 将两个文本文件合并为另外一个文本文件
	 */
	public static void sequenceInputStream() throws IOException {
		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");
		InputStream input1 = new FileInputStream(file1);
		InputStream input2 = new FileInputStream(file2);
		OutputStream output = new FileOutputStream(file3);
		// 合并流
		SequenceInputStream sis = new SequenceInputStream(input1, input2);
		int temp = 0;
		while ((temp = sis.read()) != -1) {
			output.write(temp);
		}
		input1.close();
		input2.close();
		output.close();
		sis.close();
	}

 

 27.文件压缩 ZipOutputStream类

// 压缩一个文件的例子
	public static void zipOutputStream(String[] args) throws IOException {
		File file = new File("d:" + File.separator + "hello.txt");
		File zipFile = new File("d:" + File.separator + "hello.zip");
		InputStream input = new FileInputStream(file);
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
				zipFile));
		zipOut.putNextEntry(new ZipEntry(file.getName()));
		// 设置注释
		zipOut.setComment("hello");
		int temp = 0;
		while ((temp = input.read()) != -1) {
			zipOut.write(temp);
		}
		input.close();
		zipOut.close();
	}

 

 28.文件压缩 ZipOutputStream类

/**
	 * 一次性压缩多个文件
	 */
	public static void zipOutputStream1() throws IOException {
		// 要被压缩的文件夹
		File file = new File("d:" + File.separator + "temp");
		File zipFile = new File("d:" + File.separator + "zipFile.zip");
		InputStream input = null;
		ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
				zipFile));
		zipOut.setComment("hello");
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; ++i) {
				input = new FileInputStream(files[i]);
				zipOut.putNextEntry(new ZipEntry(file.getName()
						+ File.separator + files[i].getName()));
				int temp = 0;
				while ((temp = input.read()) != -1) {
					zipOut.write(temp);
				}
				input.close();
			}
		}
		zipOut.close();
	}

 

29.ZipFile类

/**
	 * ZipFile演示
	 */
	public static void zipFile() throws IOException {
		File file = new File("d:" + File.separator + "hello.zip");
		ZipFile zipFile = new ZipFile(file);
		System.out.println("压缩文件的名称为:" + zipFile.getName());
	}

 

/**
	 * 解压缩文件(压缩文件中只有一个文件的情况)
	 */
	public static void zipFile2() throws IOException {
		File file = new File("d:" + File.separator + "hello.zip");
		File outFile = new File("d:" + File.separator + "unZipFile.txt");
		ZipFile zipFile = new ZipFile(file);
		ZipEntry entry = zipFile.getEntry("hello.txt");
		InputStream input = zipFile.getInputStream(entry);
		OutputStream output = new FileOutputStream(outFile);
		int temp = 0;
		while ((temp = input.read()) != -1) {
			output.write(temp);
		}
		input.close();
		output.close();
	}

 

30.ZipInputStream

当我们需要解压缩多个文件的时候,ZipEntry就无法使用了,如果想操作更加复杂的压缩文件,我们就必须使用ZipInputStream类

 

/**
	 * 解压缩一个压缩文件中包含多个文件的情况
	 */
	public static void zipFile3(String[] args) throws IOException {
		File file = new File("d:" + File.separator + "zipFile.zip");
		File outFile = null;
		ZipFile zipFile = new ZipFile(file);
		ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
		ZipEntry entry = null;
		InputStream input = null;
		OutputStream output = null;
		while ((entry = zipInput.getNextEntry()) != null) {
			System.out.println("解压缩" + entry.getName() + "文件");
			outFile = new File("d:" + File.separator + entry.getName());
			if (!outFile.getParentFile().exists()) {
				outFile.getParentFile().mkdir();
			}
			if (!outFile.exists()) {
				outFile.createNewFile();
			}
			input = zipFile.getInputStream(entry);
			output = new FileOutputStream(outFile);
			int temp = 0;
			while ((temp = input.read()) != -1) {
				output.write(temp);
			}
			input.close();
			output.close();
		}
	}

 

 

31.回退流:PushbackInputStream 

 

/**
	 * 回退流操作
	 */
	public static void bushBackInputStreamDemo(String[] args)
			throws IOException {
		String str = "hello,rollenholt";
		PushbackInputStream push = null;
		ByteArrayInputStream bat = null;
		bat = new ByteArrayInputStream(str.getBytes());
		push = new PushbackInputStream(bat);
		int temp = 0;
		while ((temp = push.read()) != -1) {
			if (temp == ',') {
				push.unread(temp);
				temp = push.read();
				System.out.print("(回退" + (char) temp + ") ");
			} else {
				System.out.print((char) temp);
			}
		}
	}

 

32.取得本地的默认编码

 

/**
	 * 取得本地的默认编码
	 */
	public static void charSetDemo() {
		System.out.println("系统默认编码为:" + System.getProperty("file.encoding"));
	}

 

33.待续...........................

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics