Java基础知识之文件操作
流与文件的操作在编程中经常遇到,与C语言只有单一类型File*即可工作良好不同,Java拥有一个包含各种流类型的流家族,其数量超过60个!当然我们没必要去记住这60多个类或接口以及它们的层次结构,理解和掌握其中比较常用的类和接口即可,必要的时候查询文档或API。我们把流家族成员按照它们的使用方法来进行划分,就形成了处理字节和字符的两个单独的层次结构。 
常用的字节字符流
本文主要总结了如何使用流对文件进行相应的操作。
新建文件(夹)
createFile(String path, String name)方法在指定路径path下创建文件,如果路径不存在,就创建路径,如果文件已存在,不做操作。
createDir(String name)方法创建指定的目录name。
createDir(String path, String name)方法在指定路径path下创建文件夹name。
/**
* @description 根据路径创建文件
* @param path 路径 e.g. F:\temp
* @param name 文件名 e.g. hello.txt
* @return
*/
public File createFile(String path, String name) {
File file = new File(path);
try {
if(!file.exists()) {
file.mkdirs();
}
file = new File(path + File.separator + name);
if(!file.exists()) {
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
return file;
} /**
* @description 创建文件目录
* @param name e.g. F:\temp\hello\world
* @return
* @throws IOException
*/
public File createDir(String name) throws IOException {
File file = new File(name);
if(!file.exists()) {
file.mkdirs();
}
return file;
} /**
* @description 根据路径创建文件夹
* @param path 路径 e.g. F:\temp
* @param name 文件夹名 e.g. hello
* @return
* @throws IOException
*/
public File createDir(String path, String name) throws IOException {
File file = new File(path + File.separator + name);
if(!file.exists()) {
file.mkdirs();
}
return file;
}
删除文件(夹)
删除指定文件或文件夹,如果传入的参数是文件,则直接删除,如果是目录,递归调用方法,删除该目录下所有文件和目录。
/**
* @description 删除文件(夹)
* @param file
* @throws IOException
*/
public void deleteFile(File file) throws IOException {
if(file.exists()) {
if(file.isFile()) {
file.delete();
}else if(file.isDirectory()){
File[] files = file.listFiles();
for(File item : files) {
deleteFile(item);
}
file.delete();
}
}else {
throw new FileNotFoundException();
}
}
读写文件
文件的读操作,使用带缓冲的字节流,以字节的形式读取文件,并写到参数指定的输出流out。
文件的写操作,使用带缓冲的字节流,从参数指定的输入流in读取,并以字节形式写到目标文件。
/**
* @description 读文件
* @param name 源文件
* @param out 输出流
* @throws FileNotFoundException
*/
public void readFile(File name, OutputStream out) throws FileNotFoundException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(name));
BufferedOutputStream bos = new BufferedOutputStream(out);
int len = 0;
byte[] buffer = new byte[1024];
try {
while((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* @description 写文件
* @param name 目标文件
* @param in 输入流
* @throws FileNotFoundException
*/
public void writeFile(File name, InputStream in) throws FileNotFoundException {
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name));
int len = 0;
byte[] buffer = new byte[1024];
try {
while((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件(夹)拷贝
文件拷贝,源文件src可以是文件或是目录,目标文件desc为目录。如果src是文件,直接拷贝到desc路径下;如果src是目录,首先在desc目录下创建该目录,然后遍历src目录下所有文件和目录,递归调用拷贝方法,最终实现整个文件的拷贝。
/**
* @description 拷贝文件
* @param src 源文件(夹) e.g. F:\hello
* @param desc 目标文件夹 e.g. F:\world
*/
public void copyFile(File src, File desc){
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
if(src.isFile()) {
desc = createFile(desc.getCanonicalPath(), src.getName());
in = new BufferedInputStream(new FileInputStream(src));
out = new BufferedOutputStream(new FileOutputStream(desc));
int len = 0;
byte[] buffer = new byte[1024];
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush();
}
} else if (src.isDirectory()) {
desc = createDir(desc.getCanonicalPath(), src.getName());
File[] files = src.listFiles();
for(File item : files) {
copyFile(item, desc);
}
} else {
throw new FileNotFoundException();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
文件目录遍历
遍历参数指定目录下的所有文件和目录,感兴趣可以做成树形结构。
/**
* @description 遍历文件目录
* @param file
* @throws IOException
*/
public void traverseFile(File file) throws IOException {
if(file.isFile()) {
//do something you like
} else if(file.isDirectory()) {
File[] list = file.listFiles();
for(File item : list) {
traverseFile(item);
}
} else {
throw new FileNotFoundException();
}
}
Java基础知识之文件操作的更多相关文章
- Java基础知识系列——文件操作
对文件进行操作在编程中比较少用,但是我最近有一个任务需要用到对文件操作. 对文件有如下操作形式: 1.创建新的文件(夹) File fileName = new File("C:/myfil ...
- golang基础知识之文件操作
读取文件所有内容以及获得文件操作对象 package mainimport ( "bufio" "fmt" "io" "io/io ...
- Python基础知识(八)----文件操作
文件操作 一丶文件操作初识 ###f=open('文件名','模式',编码): #open() # 调用操作系统打开文件 #mode #对文件的操作方式 #encoding # 文件的编码格式 存储编 ...
- python基础知识-day7(文件操作)
1.文件IO操作: 1)操作文件使用的函数是open() 2)操作文件的模式: a.r:读取文件 b.w:往文件里边写内容(先删除文件里边已有的内容) c.a:是追加(在文件基础上写入新的内容) d. ...
- Java基础知识系列——目录操作
Java对目录操作的许多方法与上一篇文件操作的方法很多是一样的. java.io.File file = new File( "D:\1\2\3\4"); 1.递归创建目录 fil ...
- python基础知识六 文件的基本操作+菜中菜
基础知识六 文件操作 open():打开 file:文件的位置(路径) mode:操作文件模式 encoding:文件编码方式 f :文件句柄 f = open("1.t ...
- Java基础知识(壹)
写在前面的话 这篇博客,是很早之前自己的学习Java基础知识的,所记录的内容,仅仅是当时学习的一个总结随笔.现在分享出来,希望能帮助大家,如有不足的,希望大家支出. 后续会继续分享基础知识手记.希望能 ...
- java基础知识小总结【转】
java基础知识小总结 在一个独立的原始程序里,只能有一个 public 类,却可以有许多 non-public 类.此外,若是在一个 Java 程序中没有一个类是 public,那么该 Java 程 ...
- JAVA基础知识之网络编程——-网络基础(Java的http get和post请求,多线程下载)
本文主要介绍java.net下为网络编程提供的一些基础包,InetAddress代表一个IP协议对象,可以用来获取IP地址,Host name之类的信息.URL和URLConnect可以用来访问web ...
随机推荐
- 启用密码管理之前创建的用户连接Oracle报ORA-28002处理一则
处理方法其实很简单.只要: alter user <username> identified by <same password>; 这个操作后,恢复正常了 下面作个 ...
- DBMS_LOB包的使用
DBMS_LOB包的使用 1. dbms_lob.append( dest_lob IN OUT NOCOPY BLOB, src_lob IN BLOB) dbms_lob.appen ...
- Redis简介与简单安装
Redis简介与简单安装 一.NoSQL的风生水起 1.1 后Web2.0时代的发展要求 随着互联网Web2.0网站的兴起,传统的关系数据库在应付Web2.0网站,特别是超大规模和高并发的SNS类 ...
- MVC 5 的 EF6 Code First 入门 系列:排序、筛选和分页
这是微软官方SignalR 2.0教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第三篇:排序.筛选 ...
- Bootstrap 布局
bootstrap提供的布局主要有两种,固定布局和流动布局. Bootstrap 固定布局 用法 <body> <div class="container"> ...
- Asp.net MVC的Model Binder工作流程以及扩展方法(1)
Asp.net MVC的Model Binder工作流程以及扩展方法(1)2014-03-19 08:02 by JustRun, 523 阅读, 4 评论, 收藏, 编辑 在Asp.net MVC中 ...
- JavaScript里的依赖注入
JavaScript里的依赖注入 我喜欢引用这句话,“程序是对复杂性的管理”.计算机世界是一个巨大的抽象建筑群.我们简单的包装一些东西然后发布新工具,周而复始.现在思考下,你所使用的语言包括的一些内建 ...
- iOS基础 - UITableView的数据源和代理
一.UITableView的代理方法 #pragma mark 每一行的高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtI ...
- C#自定义配置文件节点
老实说,在以前没写个自定义配置节点之前,我都是写到一个很常用的节点里面,就是appSettings里add,然后再对各个节点的value值进行字符串分割操作,根据各种分割字符嵌套循环处理,后来看到一些 ...
- C#通过接口与线程通信(捕获线程状态)介绍
C#通过接口与线程通信(捕获线程状态)介绍 摘要:本文介绍C#通过接口与线程通信(捕获线程状态),并提供简单的示例代码供参考. 提示:本文所提到的线程状态变化,并不是指线程启动.暂停.停止,而是说线程 ...