流与文件的操作在编程中经常遇到,与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基础知识之文件操作的更多相关文章

  1. Java基础知识系列——文件操作

    对文件进行操作在编程中比较少用,但是我最近有一个任务需要用到对文件操作. 对文件有如下操作形式: 1.创建新的文件(夹) File fileName = new File("C:/myfil ...

  2. golang基础知识之文件操作

    读取文件所有内容以及获得文件操作对象 package mainimport ( "bufio" "fmt" "io" "io/io ...

  3. Python基础知识(八)----文件操作

    文件操作 一丶文件操作初识 ###f=open('文件名','模式',编码): #open() # 调用操作系统打开文件 #mode #对文件的操作方式 #encoding # 文件的编码格式 存储编 ...

  4. python基础知识-day7(文件操作)

    1.文件IO操作: 1)操作文件使用的函数是open() 2)操作文件的模式: a.r:读取文件 b.w:往文件里边写内容(先删除文件里边已有的内容) c.a:是追加(在文件基础上写入新的内容) d. ...

  5. Java基础知识系列——目录操作

    Java对目录操作的许多方法与上一篇文件操作的方法很多是一样的. java.io.File file = new File( "D:\1\2\3\4"); 1.递归创建目录 fil ...

  6. python基础知识六 文件的基本操作+菜中菜

    基础知识六 文件操作 ​ open():打开 ​ file:文件的位置(路径) ​ mode:操作文件模式 ​ encoding:文件编码方式 ​ f :文件句柄 f = open("1.t ...

  7. Java基础知识(壹)

    写在前面的话 这篇博客,是很早之前自己的学习Java基础知识的,所记录的内容,仅仅是当时学习的一个总结随笔.现在分享出来,希望能帮助大家,如有不足的,希望大家支出. 后续会继续分享基础知识手记.希望能 ...

  8. java基础知识小总结【转】

    java基础知识小总结 在一个独立的原始程序里,只能有一个 public 类,却可以有许多 non-public 类.此外,若是在一个 Java 程序中没有一个类是 public,那么该 Java 程 ...

  9. JAVA基础知识之网络编程——-网络基础(Java的http get和post请求,多线程下载)

    本文主要介绍java.net下为网络编程提供的一些基础包,InetAddress代表一个IP协议对象,可以用来获取IP地址,Host name之类的信息.URL和URLConnect可以用来访问web ...

随机推荐

  1. VS 文件自动定位功能

    在Visual Studio 中,当你在所有打开的文件中进行切换时,在Solution Explorer中也会自定定位到这个文件的目录下面,这个功能用来查找当前文件是非常有用.在Tools->O ...

  2. Javascript多线程引擎(一)

    Javascript多线程引擎(一) Javascript 天生是单线程的语言, 不支持synchronized等线程操作, 但是这便不妨碍Javascript作为web语言中最具有魅力语言之一. 虽 ...

  3. 取得ASKII码值和汉语拼音

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAXMAAACmCAIAAACnXPjtAAAgAElEQVR4nO2de3wb1YHv56+7e/fe/e ...

  4. Memory Dump 分析器

    Visual Studio 2013 新功能 Memory Dump 分析器   TechEd2013 发现新功能 12月5日和6日,在国家会议中心参加了微软的 TechEd2013 技术大会,了解了 ...

  5. nutch solr 配置

    http://blog.csdn.net/panjunbiao/article/details/12171147 后半部分实践通过

  6. discuz的门户文章页中增加百度分享代码

    discuz虽然有百度分享插件,但是不太想用,于是自己手动添加了百度分享代码: 一.在http://share.baidu.com/地址中申请设置自己的百度分享代码,选择的风格完全按照个人喜好进行选择 ...

  7. IOS7配置自动布局的约束

    上一篇博客记录了怎么使用代码对视图进行约束,原文:点击打开链接 这次记录一下关于自动布局的例子, 1.创建一个Single View Application : 2.选择自动布局: 3.拖拽两个Tex ...

  8. CSS3/jQuery自定义弹出窗口

    简单演示一下,精简了演示效果和css样式文件,更利于在项目中的实际应用 引入style.css   index.js <!DOCTYPE HTML PUBLIC "-//W3C//DT ...

  9. jQuery特殊符号转义

    我们在使用jquery选择器的时候 对一些ID属性中有特殊符号的地方需要进行转义. 列举部分如下: <input id="entity.username" type=&quo ...

  10. C#山寨版本拨号客户端

    C#山寨版本[天翼拨号客户端]---内含详细抓包,模拟数据---万事俱备,只欠东风.   本帖子本来最初是发在CSDN上的,回复的也有十几个,但没有一个有技术含量的回复....特来此讨论,请教,请各位 ...