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;
}

 

 

03-21
<think>好的,我现在需要处理用户关于Java IO的问题。用户希望了解Java IO的概念或者解决相关问题,特别是询问教程和故障排除的方法。首先,我得回顾一下Java IO的基础知识,确保自己理解正确,然后组织回答的结构。 首先,Java IO主要涉及输入输出流,用于处理数据的读写。核心包是java.io,里面有很多类,比如File、InputStream、OutputStream、Reader、Writer等。用户可能需要知道这些类的层次结构和使用方法。 接下来,常见的IO操作包括文件读写、网络通信、序列化等。比如,FileInputStream和FileOutputStream用于字节流,而FileReader和FileWriter用于字符流。缓冲流(BufferedInputStream等)可以提高效率,这部分应该提到。 然后,异常处理是Java IO中很重要的一部分,比如IOException,需要正确处理try-with-resources来自动关闭流,避免资源泄漏。这部分用户可能在故障排除时会遇到问题,比如未正确关闭流导致文件锁定或资源耗尽。 关于教程,Oracle的官方文档是权威资源,应该引用。比如引用[3]提到了JSP的信息,但用户需要的是IO的教程,可能需要检查是否有其他引用相关。不过用户给出的引用中,引用[1]是关于JDK 7的故障排除工具,可能和调试IO问题相关,比如使用jdb进行调试。引用[5]提到字节码信息,可能和IO关系不大,但故障排除时可能需要查看异常堆栈,这可能涉及字节码或类加载的问题。 对于故障排除,常见问题包括文件路径错误、权限问题、字符编码不一致导致的乱码,或者流未正确关闭。比如,文件找不到可能是因为相对路径的当前工作目录与预期不符,或者文件被其他进程占用。这时候需要检查路径是否正确,是否有读取权限,使用绝对路径测试,或者使用工具如Process Explorer查看文件句柄。 此外,NIO(New IO)在Java 1.4引入,提供了非阻塞IO和通道等高效处理方式,用户可能也需要了解NIO和传统IO的区别,比如使用Channel和Buffer的方式,或者使用Files类简化操作。 在组织回答时,需要分步骤讲解,比如先介绍核心概念,然后常见操作,接着是故障排除技巧,最后提供学习资源和相关工具。同时,生成的问题要围绕Java IO的进一步学习,比如NIO、性能优化、常见异常处理等。 需要确保回答中的LaTeX格式正确,比如类名和方法名可能需要用代码块,而数学表达式则用$...$。例如,文件路径的转义可能需要讨论,比如在字符串中使用反斜杠需要转义,写成`"C:\\\\path\\\\to\\\\file"`,但这里可能不需要数学表达式,所以可能不需要用到LaTeX的公式部分。 检查用户提供的引用,是否有与IO相关的资源。引用[4]是关于安卓USB驱动的,可能不相关。引用[2]关于反射,可能也不直接相关,但故障排除时可能会用到反射来检查类路径或资源加载,这可能间接相关,但可能不需要特别提到。 总结回答结构: 1. Java IO核心概念:流、字节流与字符流、缓冲流、NIO。 2. 常见操作:文件读写示例代码。 3. 故障排除:常见问题及解决方法,如路径、权限、编码、资源泄漏。 4. 学习资源:官方教程、工具(如jdb)。 5. 相关问题:如何选择IO和NIO,处理大文件,字符编码问题,关闭资源方法,常见异常处理。 需要确保回答中的引用正确,比如引用[1]关于JDK工具,可能在故障排除时使用jdb或者jstack等工具分析问题,可以提到。引用[3]的链接虽然是JSP,但Oracle的Java EE教程可能包含IO相关内容,需要检查链接是否有效,但用户提供的链接可能已失效,需要注意。不过用户给出的引用可能有误,比如引用[3]的网址是javaee.github.io,可能是正确的,但需要确认是否有IO相关部分。 最后,代码示例需要正确,比如使用try-with-resources来读取文件,展示正确的异常处理方式。同时,确保所有技术术语准确,例如InputStreamReader处理字符编码,BufferedReader提高读取效率。 可能的问题点:用户提供的引用中是否有直接关于Java IO的内容?引用[1]提到JDK工具,可以用于调试IO问题,比如使用jdb调试应用程序,或者在出现IO异常时分析线程状态。引用[5]关于字节码信息,可能与IO问题关系不大,但类加载时找不到资源文件可能会涉及,需要看具体情况。 因此,在故障排除部分,可以建议使用JDK工具如jstack检查是否有线程阻塞在IO操作,或者使用jdb进行调试,引用[1]。同时,处理资源泄漏时,可以使用try-with-resources来自动关闭流,这是Java 7的特性,可能需要提到。 综上所述,回答的结构应该是先介绍核心概念,然后示例代码,接着故障排除步骤,引用相关资源,最后生成相关问题。</think>### Java IO 概念与问题排查指南 #### 一、核心概念 Java IO(输入输出)用于处理数据读写,核心包为 `java.io`,主要分为两类: 1. **字节流**:处理二进制数据,基类为 `InputStream` 和 `OutputStream`,例如 `FileInputStream` 和 `BufferedOutputStream`。 2. **字符流**:处理文本数据,基类为 `Reader` 和 `Writer`,例如 `FileReader` 和 `BufferedWriter`。 3. **NIO(New IO)**:Java 1.4 引入,通过 `Channel` 和 `Buffer` 实现高效非阻塞操作,例如 `Files.readAllLines()`[^1]。 #### 二、常见操作示例 1. **文件读取(字符流)**: ```java try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } ``` 2. **文件写入(字节流)**: ```java try (OutputStream out = new BufferedOutputStream(new FileOutputStream("output.dat"))) { out.write("Hello".getBytes()); } catch (IOException e) { e.printStackTrace(); } ``` #### 三、故障排查技巧 1. **文件路径问题** - 使用绝对路径或检查工作目录:`System.getProperty("user.dir")`。 - 路径分隔符兼容性:使用 `File.separator` 替代硬编码的 `/` 或 `\`。 2. **权限与资源占用** - 确认文件可读/写:`file.canRead()` 和 `file.canWrite()`。 - 确保流正确关闭:使用 **try-with-resources**(Java 7+)避免资源泄漏。 3. **字符编码问题** - 指定编码格式:例如 `new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8)`。 4. **调试工具** - 使用 `jdb`(Java Debugger)追踪 IO 异常堆栈[^1]。 - 通过 `jstack` 分析线程阻塞(如网络 IO 超时)。 #### 四、学习资源 1. **官方教程** - [Oracle Java IO 教程](https://docs.oracle.com/javase/tutorial/essential/io/)(涵盖基础与 NIO)。 2. **进阶内容** - Java NIO.2(Java 7+)的 `Path` 和 `Files` 类[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值