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 ...
随机推荐
- leetcode[105] Construct Binary Tree from Inorder and Postorder Traversal
代码实现:给定一个中序遍历和后序遍历怎么构造出这颗树!(假定树中没有重复的数字) 因为没有规定是左小右大的树,所以我们随意画一颗数,来进行判断应该是满足题意的. 3 / \ 2 4 /\ / \1 6 ...
- sugarcrm关于邮件设置几个不好理解的地方
陈沙克日志 把我的过程记录下来,以免以后忘了 2008-06-11 12:32 sugarcrm关于邮件设置几个不好理解的地方 最近看sugarcrm的使用,别的基本使用,没有什么问题,几天就 ...
- vs10创建sqlclr部署失败
将项目解决方案改为3.5,调试OK:
- poj3519 Lucky Coins Sequence矩阵快速幂
Lucky Coins Sequence Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- hadoop集群的搭建与配置(2)
对解压过后的文件进行从命名 把"/usr/hadoop"读权限分配给hadoop用户(非常重要) 配置完之后我们要创建一个tmp文件供以后的使用 然后对我们的hadoop进行配置文 ...
- 1572: [Usaco2009 Open]工作安排Job[贪心]
Description Farmer John 有太多的工作要做啊!!!!!!!!为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间. 他的工作日从0时刻开始,有1000000000个单 ...
- c#多选下拉框(ComboBox)
代码如下 using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawi ...
- TLS之上的HTTP
1.介绍 HTTP[RFC2616]最初是在INTERNET上不用密码的应用.但随着HTTP的敏感性应用日益增加,对安全性的要求也随之增加.SSL及其后继TLS[RFC2246]提供了面向通道的安全性 ...
- iphone手机用wireshark抓包
ios连上电脑 查看udid. 启动虚拟接口 rvictl -s 7e65eeaa55a1e43dbdfb44a02f9871f1f304043e 打开mac权限 sudo chmod 644 /de ...
- C# 遍历本地网络
public static bool IsHNetCfgWayConnected(string opName) { NetSharingManagerClass netSharingMgr = new ...