`
jaesonchen
  • 浏览: 313416 次
  • 来自: ...
社区版块
存档分类
最新评论

java IO

 
阅读更多
package com.jaeson.javastudy;

import java.io.*;
import java.util.zip.*;

public class IOTest {

	//跨平台的文件分割符
	static void separator() {
		System.out.println(File.separator);		// \
        System.out.println(File.pathSeparator);	// ;
	}
	//创建文件,创建成功返回true,当文件名已存在时返回false
	static void create() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello.txt";
        File f = new File(fileName);
        f.createNewFile();
	}
	//删除文件或目录,删除目录时,File代表的目录必须是空的。
	//java.nio.file.Files的delete方法,在无法删除一个文件是抛出IOException。
	static void delete() {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello.txt";
        File f = new File(fileName);
        if (f.exists()) {
            f.delete();
        } else {
            System.out.println("文件不存在");
        }
	}
	//创建目录
	static void mkdir() {
		String fileName = "C:" + File.separator + "hello";
        File f = new File(fileName);
        f.mkdir();
	}
	//列出指定目录的全部文件(包括隐藏文件)
	//使用list返回的是String数组,只包含文件名。
	static void list() {
		String fileName = "C:" + File.separator + "hello";
	    File f = new File(fileName);
	    String[] str = f.list();
	    for (int i = 0; i < str.length; i++) {
	        System.out.println(str[i]);
	    }
	}
	//列出指定目录的全部文件(包括隐藏文件)
	//listFiles返回的是File的数组,包含完整路径。
	static void listFile() {
		String fileName = "C:" + File.separator + "hello";
        File f = new File(fileName);
        File[] files = f.listFiles();
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i]);
        }
	}
	//判断一个指定的路径是否为目录
	static void isDirectory() {
		String fileName = "C:" + File.separator + "hello";
        File f = new File(fileName);
        if (f.isDirectory()) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
	}
	//搜索指定目录的全部内容
	static void listAll() {
		String fileName = "C:" + File.separator + "hello";
        File f = new File(fileName);
        print(f);
	}
	private 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);
            }
		}
	}
	//写入字节流
	static void outputStream() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello.txt";
		OutputStream out = new FileOutputStream(new File(fileName));
		String str = "你好";
		//使用系统默认编码
		byte[] b = str.getBytes();
		out.write(b);
		b = "北京".getBytes();
		for (int i = 0; i < b.length; i++) {
			out.write(b[i]);
		}
		out.close();
	}
	//向文件中追加新内容
	static void appendFile() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello.txt";
		OutputStream out = new FileOutputStream(new File(fileName), true);
		String str="\r\njaesonchen";
		byte[] b = str.getBytes();
		out.write(b);
		out.close();
	}
	//读取文件内容
	static void inputStream() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello.txt";
		InputStream in = new FileInputStream(new File(fileName));
        byte[] b = new byte[1024];
        int len = in.read(b);
        in.close();
        System.out.println("读入长度为:" + len);
        System.out.println(new String(b, 0, len));
	}
	//一个个字节读
	static void inputStream2() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello.txt";
		InputStream in = new FileInputStream(new File(fileName));
        byte[] b = new byte[1024];
        int temp = 0;
        int i = 0;
        while ((temp = in.read()) != -1 && i < 1024) {
        	b[i++] = (byte) temp;
        }
        in.close();
        System.out.println(new String(b, 0, i));
	}
	
	//写入字符流
	static void writer() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello_writer.txt";
		Writer out = new FileWriter(new File(fileName));
		//文件追加
		//Writer out = new FileWriter(new File(fileName), true);
        String str = "hello";
        out.write(str);
        out.close();
	}
	//读取字符流
	static void reader() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "hello_writer.txt";
		Reader in = new FileReader(new File(fileName));
		char[] ch = new char[1024];
		int temp = 0;
        int i = 0;
        while((temp = in.read()) != -1 && i < 1024)
            ch[i++] = (char) temp;
        in.close();
        System.out.println(new String(ch, 0, i));
	}
	//文件复制
	static void fileCopy() throws IOException {
		String fileName1 = "C:" + File.separator + "hello" + File.separator + "hello.txt";
		String fileName2 = "C:" + File.separator + "hello" + File.separator + "hello_copy.txt";
		InputStream in = new FileInputStream(new File(fileName1));
        OutputStream out = new FileOutputStream(new File(fileName2));
        int temp=0;
        while((temp = in.read()) != -1)
        	out.write(temp);
        in.close();
        out.close(); 
	}
	//OutputStreramWriter 和InputStreamReader
	//将字节输出流转化为字符输出流
	static void stream2writer() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "helloworld.txt";
        Writer out = new OutputStreamWriter(new FileOutputStream(new File(fileName)));
        out.write("hello world");
        out.close();
	}
	//将字节输入流变为字符输入流
	static void stream2reader() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "helloworld.txt";
        Reader in = new InputStreamReader(new FileInputStream(new File(fileName)));
        char[] ch = new char[1024];
        int temp = 0;
        int i = 0;
        while((temp = in.read()) != -1 && i < 1024)
            ch[i++] = (char) temp;
        in.close();
        System.out.println(new String(ch, 0, i));
	}
	//ByteArrayInputStream 将内容写入内存
	//ByteArrayOutputStream 将内容从内存输出
	static void byteArrayStream() throws IOException {
		String str="ROLLENHOLT";
        ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int temp = 0;
        while((temp = in.read()) != -1){
            char ch = (char) temp;
            out.write(Character.toLowerCase(ch));
        }
        String outStr = out.toString();
        in.close();
        out.close();
        System.out.println(outStr);
	}
	
	//PrintStream打印流
	static void printStream() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "printstream.txt";
		PrintStream print = new PrintStream(new FileOutputStream(new File(fileName)));
        print.println(true);
        print.println("hello");
        //格式化输出
        print.printf("姓名:%s  年龄:%d", "jaesonchen", 30);
        print.close();
        //向控制台输出
        OutputStream out = System.out;
        out.write("hello world".getBytes());
        out.close();
	}
	//输入输出重定向
	static void redirect() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "printstream.txt";
		
		System.setIn(new FileInputStream(new File(fileName)));
        byte[] bytes = new byte[1024];
        int len = 0;
        len = System.in.read(bytes);
        System.out.println("读入的内容为:" + new String(bytes, 0, len));
        
        fileName = "C:" + File.separator + "hello" + File.separator + "redirect.txt";
        System.setOut(new PrintStream(new FileOutputStream(new File(fileName))));
        System.out.println("这些内容在文件中才能看到哦!"); 
	}
	
	//BufferedReader只能接受字符流的缓冲区
	static void bufferReader() throws IOException {
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
        String str = null;
        System.out.println("请输入内容");
        str = buf.readLine();
        System.out.println("你输入的内容是:" + str);
	}
	//数据操作流DataOutputStream、DataInputStream
	static void dataOutput() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "dataoutput.txt";
		DataOutputStream out = new DataOutputStream(new FileOutputStream(new File(fileName)));
		out.writeChar('A');
		out.writeInt(37);
		out.writeBoolean(false);
        out.close();
	}
	static void dataInput() throws IOException {
		String fileName = "C:" + File.separator + "hello" + File.separator + "dataoutput.txt";
		DataInputStream input = new DataInputStream(new FileInputStream(new File(fileName)));
		System.out.println(input.readChar());
		System.out.println(input.readInt());
		System.out.println(input.readBoolean());
		input.close();
	}
	//SequenceInputStream 合并流 
	static void sequenceStream() throws IOException {
		File file1 = new File("C:" + File.separator + "hello" + File.separator + "dataoutput.txt");
        File file2 = new File("C:" + File.separator + "hello" + File.separator + "redirect.txt");
        File file3 = new File("C:" + File.separator + "hello" + File.separator + "sequence.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();
	}
	//文件压缩 ZipOutputStream
	static void zipOutputStream() throws IOException {
		File file = new File("C:" + File.separator + "hello" + File.separator + "hello.txt");
        File zipFile = new File("C:" + File.separator + "hello" + 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 world");
        int temp = 0;
        while ((temp = input.read()) != -1)
            zipOut.write(temp);
        input.close();
        zipOut.close();
	}
	//压缩多个文件
	static void zipOutputStream2() throws IOException {
		// 要被压缩的文件夹
        File file = new File("C:" + File.separator + "hello" + File.separator + "test");
        File zipFile = new File("C:" + File.separator + "hello" + File.separator + "hello.zip");
        InputStream input = null;
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length && !files[i].isDirectory(); 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();
	}
	//解压缩
	static void zipExtract() throws IOException {
		 File file = new File("C:" + File.separator + "hello" + File.separator + "hello.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("C:" + File.separator + "hello" 
	            		+ File.separator + "extract" + 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();
	     }
	     zipInput.close();
	     zipFile.close();
	}
	//ObjectInputStream和ObjectOutputStream 对象序列化
	static void objectOutputStream() throws IOException {
		File file = new File("C:" + File.separator + "hello" + File.separator + "object.txt");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(new Student("jaeson", 30));
        oos.close();
	}
	static void objectInputStream() throws Exception {
		File file = new File("C:" + File.separator + "hello" + File.separator + "object.txt");
		ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
        Object obj = input.readObject();
        input.close();
        System.out.println(obj);
	}
	
	public static void main(String[] args) throws Exception {
		//objectInputStream();
		//objectOutputStream();
		//zipExtract();
		//zipOutputStream2();
		//zipOutputStream();
		//sequenceStream();
		//dataInput();
		//bufferReader();
		//redirect();
		//printStream();
		//byteArrayStream();
		//stream2reader();
		//stream2writer();
		//fileCopy();
		//reader();
		//writer();
		//inputStream2();
		//inputStream();
		//appendFile();
		//outputStream();
		//separator();
		//create();
		//delete();
		//mkdir();
		//list();
		//listFile();
		//isDirectory();
		//listAll();
		/*Send send = new Send();
        Recive recive = new Recive();
        //管道连接
        send.getOut().connect(recive.getInput());
        new Thread(send).start();
        new Thread(recive).start();*/
	}
}
//PipedOutputStream 管道输出流
//PipedInputStream 管道输入流
//发送消息类
class Send implements Runnable {
    private PipedOutputStream out = null;
    public Send() {
        out = new PipedOutputStream();
    }
    public PipedOutputStream getOut() {
        return this.out;
    }
    @Override public void run() {
        String message = "hello jaesonchen";
        try {
            out.write(message.getBytes());
            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;
    }
    @Override public void run() {
        byte[] b=new byte[1024];
        int len=0;
        try {
            len = this.input.read(b);
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("接受的内容为 " + new String(b, 0, len));
    }
}
//Serializable
@SuppressWarnings("all")
class Student implements Serializable{
    public Student() { }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override public String toString() {
        return "姓名:" + name + "  年龄:" + age;
    }
    //transient成员不会被序列化
    private transient String name;
    private int age;
}

 

 

分享到:
评论

相关推荐

    Java IO应届生培训讲义

    Java IO应届生培训讲义是一份面向刚毕业的大学生进行Java IO相关知识的培训资料,它涵盖了Java IO的基础知识、不同的IO模型以及Java中的BIO、NIO和AIO高级IO类库。下面详细解释这些知识点: 1. 用户空间和内核空间 ...

    Java IO知识点

    Java IO(Input/Output)是Java编程语言中用于处理输入输出操作的重要部分,涉及文件、网络、内存等数据传输。本文将深入探讨Java IO的基本概念、分类、选择流的策略以及常用的流类型。 首先,File类是Java IO的...

    java IO教程,java IO教程,java IO教程

    java IO教程,java IO教程,java IO教程,java IO教程java IO教程java IO教程java IO教程java IO教程,java IO教程java IO教程java IO教程java IO教程java IO教程,java IO教程,java IO教程,java IO教程,java IO...

    java io 结构图

    Java IO(Input/Output)是Java编程语言中用于处理输入和输出操作的重要组成部分。它提供了一整套类库,使得开发者能够有效地读取和写入数据到不同的源和目标,如文件、网络、内存缓冲区等。Java IO体系结构设计得...

    Java IO_NIO

    Java IO(Input/Output)是Java编程语言中用于处理输入输出操作的基础框架,它提供了丰富的类库,使得程序能够与各种设备、文件、网络进行数据交互。然而,传统的IO模型在处理大量并发连接时表现出效率较低的问题,...

    java IO.chm

    《Java IO.chm》是一个关于Java输入/输出(IO)技术的压缩文件,其中包含了丰富的资料,适合开发者深入理解和学习Java IO系统。这篇详细的总结将围绕Java IO体系结构、核心类、流的概念、缓冲区、转换流、字符集、...

    Java教程之javaIO详解

    Java IO 详解 Java IO(Input/Output)是 Java 语言中用于处理输入输出操作的类库,提供了大量的类和方法来实现文件、网络、字节流等方面的输入输出操作。下面对 Java IO 中的重要知识点进行详细说明。 一、File ...

    Java IO处理类的汇总

    Java IO处理类是Java平台中用于输入输出操作的核心部分,它允许程序与各种类型的输入源(如文件、网络连接)以及输出目标(如显示器、打印机)进行交互。本篇文章将全面解析Java IO处理类,包括基本概念、常用类库、...

    Java IO 编程集合

    Java IO编程是Java平台中处理输入输出操作的重要组成部分,它提供了丰富的类库,使得开发者能够高效地进行数据的读取、写入、流的管理和转换。在这个集合中,我们主要探讨的是Java IO在文件读写方面的实践应用。 一...

    JAVA IO流技术

    Java IO流技术是Java平台中用于处理输入输出的重要机制,其核心在于数据的传输,从数据源到程序或从程序到目的地。在Java中,流分为两大类:输入流(InputStream、Reader)和输出流(OutputStream、Writer)。输入流...

    Java IO 使用例

    在“JavaIODemo”这个示例中,可能会包含以上提到的一些或全部Java IO操作的代码实例,通过这些实例,我们可以学习如何在实际项目中应用Java IO API。实践是掌握Java IO的最佳方式,通过对这些示例的分析和运行,...

    java io.pdf

    Java IO(Input/Output)是Java编程语言中用于处理输入和输出操作的重要组成部分。它提供了丰富的类库,允许程序员在程序之间传输数据,包括从文件、网络、内存缓冲区到其他程序或系统组件。Java IO API是Java平台的...

    JavaIO流详解归纳.pdf

    JavaIO流详解归纳 Java 的核心库 java.io 提供了全面的 IO 接口,包括文件读写、标准设备输出等。Java 中 IO 是以流为基础进行输入输出的,所有数据被串行化写入输出流,或者从输入流读入。在项目开发中,IO 是非常...

    javaIo操作的基础代码

    Java IO操作是Java编程中的重要组成部分,主要用于处理输入和输出数据。在Java中,IO操作涉及到文件、字节流、字符流以及管道流等多个概念。下面将详细解释这些知识点。 首先,我们来看“文件类”。在Java中,`java...

    Java IO 与 装饰模式

    Java IO 与 装饰模式 在Java编程中,输入输出(IO)处理是程序设计中的重要组成部分,用于读取、写入和处理数据。Java IO库提供了一整套类来支持各种类型的输入输出操作,包括文件、网络、内存等。而装饰模式是一种...

    JAVA IO流缓冲字节流缓冲字符流等流经典代码示例加注释总结.rar

    2、常用21个IO流:FileWriter、FileReader、...3、JAVA IO流经典代码示例,示例从易到难。代码功能涉及字节、字符、字符串、文本文件、图片、音频、视频。演示错误用法和经典用法。 4、代码的结构可查看README文件。

    java io流 案例

    Java IO流是Java平台中的重要组成部分,用于处理输入和输出操作。它允许程序与外部设备如硬盘、网络、内存等进行数据传输。IO流的概念基于流(Stream)模型,数据以字节或字符序列的形式流动。Java IO库提供了丰富的...

    java io流学习笔记1

    Java IO流是Java编程语言中处理输入输出操作的重要部分,尤其在数据传输、文件读写等方面发挥着核心作用。本文将深入探讨Java IO流的基本概念、类型以及它们在实际开发中的应用。 首先,理解IO流的基本概念至关重要...

    Java IO 工具类大全

    Java IO(Input/Output)是Java平台中处理输入与输出数据的核心部分,它提供了丰富的类库,使得开发者能够高效地进行文件、网络、内存以及其他I/O流的操作。本篇文章将全面解析Java IO工具类,帮助你理解并掌握其在...

Global site tag (gtag.js) - Google Analytics