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 ...
随机推荐
- Solr 教程
1.Solr安装 下载jdk-8u111-windows-i586_8.0.1110.14 下载solr-6.3.0.zip 2.配置JAVA_HOME 在"系统变量"中,设置3项 ...
- 我的Android 4 学习系列之创建用户基本界面
目录 使用视图和布局 理解Fragment 优化布局 创建分辨率无关的用户界面 扩展.分组.创建和使用视图 使用适配器将数据绑定到视图 使用视图和布局 1. Android UI 几个基本概念 视图: ...
- C#使用Thrift简介,C#客户端和Java服务端相互交互
C#使用Thrift简介,C#客户端和Java服务端相互交互 本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实 ...
- 读书笔记—CLR via C#反射
前言 这本书这几年零零散散读过两三遍了,作为经典书籍,应该重复读反复读,既然我现在开始写博了,我也准备把以前觉得经典的好书重读细读一遍,并且将笔记整理到博客中,好记性不如烂笔头,同时也在写的过程中也可 ...
- windows server 2003断开远程之后自动注销用户
windows server 2003断开远程之后自动注销用户 2011-07-30 09:42:52 我来说两句 收藏 我要投稿 最近一台服务器老是断开远程之后过没多久就自动 ...
- Angularjs 与Ckeditor
Angularjs 与Ckeditor Angularjs 诞生于Google是一款优秀的前端JS框架,已经被用于Google的多款产品当中.AngularJS有着诸多特性,最为核心的是:MVC.模块 ...
- DotNET应用架构设计指南 安全 运行管理和通讯策略
DotNET应用架构设计指南(第三章:安全 运行管理和通讯策略(13-16)) 安全 运行管理和通讯策略 组织策略定义的规则是支配应用程序如何安全,如何管理,不同的应用程序组件是如何和另一组件及外部服 ...
- linux extract rar files
Extract rar-archives If you need to extract rar files in Linux, you have to download and install unr ...
- Spring注解:@Resource、@PreConstruct、@PreDestroy、@Component
要使用Spring的注解,必须在XML文件中配置有属性,告诉人家你要使用注解,Spring容器才会去加载类上的注解: <?xml version="1.0" encoding ...
- 随机函数Surprising
之前写了个用来抽取1-54号的随机函数,发现30-40出现的情况很大,就在果壳上提问了一下//听取了某个大神的建议循环了10000次之后惊喜的发现这样写出现了一大堆相同的数字! 之后有个很神大牛解答了 ...