Java学习之文件操作

这篇博客详细介绍了Java中文件操作的基础知识,包括File类的使用、文件的增删改查以及IO流的读写。作者提供了一个示例程序,演示了如何监听一个目录下的所有txt文件,读取内容并复制到另一个目录。博客还涵盖了FileInputStream和FileOutputStream的使用方法,以及如何读写文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

因为文件操作是一个非常常见的操作,在加上用法非常固定,就写一篇博客整理一下
我直接用一个小项目说明文件操作的方法,当然主要还是去看官方的api文档是最好的
我的一个demo程序是监听一个目录下的所有文件,把每一个读取每一个文件的内容,然后再将其复制到另外一个目录下。

本博客原创,转载请注明!!!
本文链接
个人博客:https://ronglin.fun/?p=143
PDF链接:见博客网站
优快云: https://blog.youkuaiyun.com/RongLin02/article/details/118736944

以下实操均是我自己写的小demo,如有错误请联系我!
查询的API内容来自以下网站,仅用于学习,如有侵权请联系我删除
一个中文API:MaTools在线中文API-JDK8

File类

对于文件的操作,我一般用File类,对于文件本身内容的操作,一般用输入输出流来完成。
有两个概念是要知道的,一个是绝对路径,还有一个是相对路径。

常用方法

1.构造方法

//从父抽象路径名和子路径名字符串创建新的 File实例。
File(File parent, String child)

//通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
File(String pathname)

//从父路径名字符串和子路径名字符串创建新的 File实例。
File(String parent, String child)

//通过将给定的 file: URI转换为抽象路径名来创建新的 File实例。
File(URI uri)

一共四种构造方法,可根据需要选择不同的方式创建File

2.增删改查

//当且仅当具有该名称的文件尚不存在时,原子地创建一个由该抽象路径名命名的新的空文件。
boolean createNewFile()

//删除由此抽象路径名表示的文件或目录。
boolean	delete()

//测试此抽象路径名表示的文件或目录是否存在。
boolean exists()

//测试此抽象路径名表示的文件是否为目录。
boolean isDirectory()

//测试此抽象路径名表示的文件是否为普通文件。不是目录,并且另外满足其他依赖于系统的条件
boolean	isFile()

//创建由此抽象路径名命名的目录。
boolean mkdir()

//重命名由此抽象路径名表示的文件。
boolean	renameTo(File dest)

//返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录。
String[]	list()
//返回一个字符串数组,命名由此抽象路径名表示的目录中满足指定过滤器的文件和目录。
String[]	list(FilenameFilter filter)
//返回一个抽象路径名数组,表示由该抽象路径名表示的目录中的文件。
File[]	listFiles()
//返回一个抽象路径名数组,表示由此抽象路径名表示的满足指定过滤器的目录中的文件和目录。
File[]	listFiles(FileFilter filter)
//返回一个抽象路径名数组,表示由此抽象路径名表示的满足指定过滤器的目录中的文件和目录。
File[]	listFiles(FilenameFilter filter)

此外还有很多常用的方法,例如获取绝对路径之类的,api中很详细,不再列出。

IO流

对于文件的读写,我一般习惯用这几个FileInputStream,FileOutputStream,FileReader,FileWriter四种流.
当然,用其他的流也是一样的
注意,所有流用完之后要记得close()

读文件

首先是读文件

FileInputStream

FileInputStream从文件系统中的文件获取输入字节。 什么文件可用取决于主机环境。
FileInputStream用于读取诸如图像数据的原始字节流。 要阅读字符串,请考虑使用FileReader 。

构造方法
//通过打开与实际文件的连接创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
FileInputStream(File file)
//创建 FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。
FileInputStream(FileDescriptor fdObj)
//通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。
FileInputStream(String name)
常用方法
//关闭此文件输入流并释放与流相关联的任何系统资源。
void	close()

//从该输入流读取一个字节的数据。
int	read()
//从该输入流读取最多 b.length个字节的数据为字节数组。
int	read(byte[] b)
//从该输入流读取最多 len字节的数据为字节数组。
int	read(byte[] b, int off, int len)
实操代码
static final int MAX = 1024*1024;
int len = 0 ;
byte[] buff = new byte[MAX];
StringBuffer buffer = new StringBuffer();
String text = null;

String path = "F:\Desktop\test.txt";
FileInputStream input = null ;

try {
	    input = new FileInputStream(path);
} catch (FileNotFoundException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
}

//读取txt文件
try {
	while(( (len = input.read(buff) )!= -1 ))
	{
		buffer.append(new String(buff,0,len,"utf-8"));
	}
} catch (IOException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
}
	text = buffer.toString();
	System.out.println("text :");
	System.out.println(text+"\n");
try {
	input.close();
} catch (IOException e) {
	// TODO Auto-generated catch block
    e.printStackTrace();
}

FileReader

阅读字符文件的便利课。
该类的构造函数假定默认字符编码和默认字节缓冲区大小是适当的。 要自己指定这些值,请在FileInputStream上构造一个InputStreamReader。
FileReader是用于读取字符流。 要读取原始字节流,请考虑使用FileInputStream 。

构造方法
//创建一个新的 FileReader ,给出 File读取
FileReader(File file)
//创建一个新的 FileReader ,给定 FileDescriptor读取。
FileReader(FileDescriptor fd)
//创建一个新的 FileReader ,给定要读取的文件的名称。
FileReader(String fileName)
常用方法
public class FileReader extends InputStreamReader

Methods inherited from class java.io.InputStreamReader
因为是继承了InputStreamReader类,方法都类似

写文件

FileOutputStream

文件输出流是用于将数据写入到输出流File或一个FileDescriptor 。
文件是否可用或可能被创建取决于底层平台。 特别是某些平台允许一次只能打开一个文件来写入一个FileOutputStream (或其他文件写入对象)。 在这种情况下,如果所涉及的文件已经打开,则此类中的构造函数将失败。
FileOutputStream用于写入诸如图像数据的原始字节流。 对于写入字符流,请考虑使用FileWriter

构造方法
//创建文件输出流以写入由指定的 File对象表示的文件。
FileOutputStream(File file)
//创建文件输出流以写入由指定的 File对象表示的文件。如果第二个参数是true ,则字节将写入文件的末尾而不是开头
FileOutputStream(File file, boolean append)
//创建文件输出流以写入指定的文件描述符,表示与文件系统中实际文件的现有连接。
FileOutputStream(FileDescriptor fdObj)
//创建文件输出流以指定的名称写入文件。
FileOutputStream(String name)
//创建文件输出流以指定的名称写入文件。如果第二个参数是true ,则字节将写入文件的末尾而不是开头。
FileOutputStream(String name, boolean append)
常用方法
//关闭此文件输入流并释放与流相关联的任何系统资源。
void	close()

//将 b.length个字节从指定的字节数组写入此文件输出流。
void	write(byte[] b)
将 len字节从位于偏移量 off的指定字节数组写入此文件输出流。
void	write(byte[] b, int off, int len)
将指定的字节写入此文件输出流。
void	write(int b)
实操代码
FileOutputStream output = null ;
String path = "F:\Desktop\test.txt";
String text = "123";
try {
	output = new FileOutputStream(path);
} catch (FileNotFoundException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
}

try {
	output.write(text.getBytes());
} catch (IOException e1) {
    // TODO Auto-generated catch block
	e1.printStackTrace();
}
try {
	output.close();
} catch (IOException e) {
	// TODO Auto-generated catch block
    e.printStackTrace();
}

FilterWriter

方便课写字符文件。 该类的构造函数假定默认字符编码和默认字节缓冲区大小是可以接受的。 要自己指定这些值,请在FileOutputStream上构造一个OutputStreamWriter。
文件是否可用或可能被创建取决于底层平台。 特别是某些平台允许一次只能打开一个文件来写入一个FileWriter (或其他文件写入对象)。 在这种情况下,如果所涉及的文件已经打开,则此类中的构造函数将失败。

FileWriter是用于写入字符流。 要编写原始字节流,请考虑使用FileOutputStream 。

构造方法
//给一个File对象构造一个FileWriter对象。
FileWriter(File file)
//给一个File对象构造一个FileWriter对象。
FileWriter(File file, boolean append)
//构造与文件描述符关联的FileWriter对象。
FileWriter(FileDescriptor fd)
//构造一个给定文件名的FileWriter对象。
FileWriter(String fileName)
//构造一个FileWriter对象,给出一个带有布尔值的文件名,表示是否附加写入的数据。
FileWriter(String fileName, boolean append)
常用方法
public class FileWriter extends OutputStreamWriter

Methods inherited from class java.io.OutputStreamWriter
因为是继承了OutputStreamWriter类,方法都类似

源代码

我的一个demo程序:
监听一个目录下的所有txt文件,读取每一个文件的内容,然后再将其复制到另外一个目录下。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ListenFile {
	
	private static final int MAX = 1024*1024;
	private String listenPath = null;
	private String savePath = null;
	private String charCode = null;
	File file = null;
	File saveFile = null;
	
	byte[] buff = new byte[MAX];
	int len = 0 ;
	String[] names = null;
	
	public ListenFile(String listenPath,String savePath,String charCode)
	{
		this.listenPath = listenPath;
		this.savePath = savePath;
		this.charCode = charCode;
		file = new File(listenPath);
		
		saveFile = new File(savePath);
		if(!saveFile.exists())
		{
			saveFile.mkdir();
		}
	}

	public boolean judgeFile()
	{
		if(!file.exists())
		{
			System.out.println("Error,listenPath not exists");
			return false;
		}
		
		if(file.isFile())
		{
			System.out.println("Error,listenPath is a file");
			return false;
		}
		
		names = file.list((dir,name)->name.endsWith(".txt"));
		
		if((names ==null)  || (names.length == 0))
		{
			System.out.println("Error,not exists TXT");
			return false;
		}
		
		return true;
	}
	
	public boolean readText()
	{
		
		for(String name : names)
		{
			String path = listenPath + "/" + name;
			len = 0 ;
			StringBuffer buffer = new StringBuffer();
			String text = null;	
			
			FileInputStream input = null ;
			FileOutputStream output = null ;
			
			try {
				input = new FileInputStream(path);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.println("Error, "+path+" not exists");
			}
			
			//读取txt文件
			try {
				
				while(( (len = input.read(buff) )!= -1 ))
				{
					buffer.append(new String(buff,0,len,charCode));
				}
				
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();		
				System.out.println("Error, "+path+" read fail");
			}
			
			//获取txt文件中的内容
			text = buffer.toString();
			System.out.println("text :");
			System.out.println(text+"\n");
			
					
			//复制文件到目录
			try {
				output = new FileOutputStream(savePath +"/"+name);
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				System.out.println("Error, "+savePath +"/"+ name+" not exists");
			}
			 
			try {
				output.write(text.getBytes());
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				System.out.println("Error, "+savePath + name+" copy fail");
			}
	
			try {
				input.close();
				output.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.println("Error,stream close fail");
			}
			
			//删除文件
			if(new File(path).delete())
			{
				System.out.println(path+" delete!");
			}
			else 
			{
				System.out.println(name+" not delete!");
			}
			
			//1s处理一个文件
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return true;	
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值