java IO

1、File常用方法
 file.createNewFile();创建文件
 file.delete();删除文件
 file.mkdir();创建目录
 file.Directory();判断一个指定的路径是否为目录

2、OutputStreramWriter 和InputStreamReader类
 整个IO类中除了字节流和字符流还包括字节和字符转换流。
 OutputStreramWriter将输出的字符流转化为字节流
 InputStreamReader将输入的字节流转换为字符流
 但是不管如何操作,最后都是以字节的形式保存在文件中的。

 Writer out=new OutputStreamWriter(new FileOutputStream(file));将字节输出流转化为字符输出流
 Reader read=new InputStreamReader(new FileInputStream(file));将字节输入流变为字符输入流

3、Scanner类,略
4、SequenceInputStream主要用来将2个流合并在一起,比如将两个txt中的内容合并为另外一个txt。
5、ObjectOutputStream类,对象需要序列化,实现Serializable接口
 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
 oos.writeObject(obj);

 ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));

 Object obj = input.readObject();


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;


public class IOTest {
	
	private static String pathFile = "d:" + File.separator + "hello.txt";
	private static String pathDir = "d:" + File.separator + "hello";
	
	public static void main(String[] args) {
//		createFileTxt();
//		deleteFile();
//		createMkdir();
//		fileList();
//		File file = new File("d:" + File.separator + "coolstor" + File.separator);
//		searchAllFile(file);
//		writeString("你好!");
//		readString();
//		writeStr("字符流!");
		readStr();
		fileCopy();
	}
	
	/**
	 * 创建文件
	 */
	private static void createFileTxt(){
		File file = new File(pathFile);
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除文件
	 */
	private static void deleteFile(){
		File file = new File(pathFile);
		if(file.exists()){
			file.delete();
		}else{
			System.out.println("文件不存在!");
		}
	}
	
	/**
	 * 创建目录
	 */
	private static void createMkdir(){
		File file = new File(pathDir);
		file.mkdir();
	}
	
	/**
	 * 使用list列出指定目录的全部文件
	 * listFiles输出的是完整路径
	 */
	private static void fileList(){
		String path = "d:" + File.separator + File.separator;
		File file = new File(path);
		if(file.isDirectory()){
			//String[] strList = file.list();//这里输出的是文件名
			File[] strList = file.listFiles();//输出完整路径
			for (int i = 0; i < strList.length; i++) {
				System.out.println("---fileList()-----" + strList[i]);
			}
		}else{
			System.out.println("该目录不存在!");
		}
	}
	/**
	 * 搜索指定目录的全部内容
	 * @param file
	 */
	private static void searchAllFile(File file){
		if(file != null){
			if(file.isDirectory()){
				File[] arrayFile = file.listFiles();
				if(arrayFile != null){
					for (int i = 0; i < arrayFile.length; i++) {
						searchAllFile(arrayFile[i]);//递归调用
					}
				}
			}else{
				System.out.println(file);
			}
		}
	}
	
	/**
	 * 字节流
	 * 向文件中写入字符串
	 * @param str
	 */
	private static void writeString(String str){
		String fileName = "d:" + File.separator + "hello.txt";
		File file = new File(fileName);
		try {
			//OutputStream os = new FileOutputStream(file);//自动创建文件
			OutputStream os = new FileOutputStream(file, true);//在文件中追加内容
			byte[] b = str.getBytes();
			os.write(b);//一次性写入
			//个字节一个字节的写入
			//for (int i = 0; i < b.length; i++) {
	        //    os.write(b[i]);
	        //}
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 字节流
	 * 向文件中read字符串
	 */
	private static void readString(){
		String fileName = "d:" + File.separator + "hello.txt";
		File file = new File(fileName);
		try {
			InputStream is = new FileInputStream(file);
			byte[] b = new byte[((int)file.length())];//((int)file.length())这里为了节省空间,计算file大小
			is.read(b);
			is.close();
			System.out.println("---readString()-----" + new String(b));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 字符流,写入字符
	 * 这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。
	 * Writer out =new FileWriter(f,true);文件中追加内容
	 */
	private static void writeStr(String str){
		String fileName = "d:" + File.separator + "hello.txt";
		File file = new File(fileName);
		try {
			Writer out = new FileWriter(file);
			out.write(str);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 字符流
	 * 从文件中读出内容
	 * 当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。
	 */
	private static void readStr(){
		String fileName = "d:" + File.separator + "hello.txt";
		File file = new File(fileName);
		char[] ch = new char[1024];
		int temp = 0;
		int count = 0;
		try {
			Reader read = new FileReader(file);
			while((temp = read.read()) != (-1)){
				ch[count++] = (char)temp;
			}
			read.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("---readStr()-----" + new String(ch,0,count));
	}
	
//	关于字节流和字符流的区别
//	实际上字节流在操作的时候本身是不会用到缓冲区的,是文件本身的直接操作的,但是字符流在操作的 时候下后是会用到缓冲区的,是通过缓冲区来操作文件的。
//	读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。
//	使用字节流好还是字符流好呢?
//	答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。
	
	/**
	 * 文件复制
	 * 基本思路是从一个文件中读入内容,边读边写入另一个文件
	 */
	private static void fileCopy(){
		String fileName1 = "d:" + File.separator + "hello.txt";
		String fileName2 = "d:" + File.separator + "hello_copy.txt";
		File file1 = new File(fileName1);
		File file2 = new File(fileName2);
		if(!file1.exists()){
			return;
		}
		
		try {
			InputStream is = new FileInputStream(file1);
			OutputStream os = new FileOutputStream(file2);
			if(is != null && os != null){
				int temp = 0;
				while((temp = is.read()) != (-1)){
					os.write(temp);
				}
			}
			is.close();
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

<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、付费专栏及课程。

余额充值