File类
File对象包含了文件中的所有字节数据,以及文件的其他详细信息。
创建File对象
//File对象包含了文件中的所有字节数据,以及文件的其他详细信息
File file;
//使用绝对路径创建文件
file = new File("d:/myFile/a/test.txt");
//通过父文件对象创建
file = new File(new File("d:/myFile"), "a/test.txt");
file = new File(new File("d:/myFile/a"),"test.txt");
//通过父文件路径创建
file = new File("d:/myFile", "a/test.txt");
常见的File的操作
创建、重命名、删除、复制、剪切、黏贴
File对象的方法
exists 判断文件是否已经存在
getAbsolutePath 获取文件的绝对路径
isFile 是否是单个的文件
isDirectory 是否是文件夹
listFiles 获取文件夹中的子文件
createNewFile 创建新文件
mkdir 创建文件夹
delete 删除
renameTo 重命名
获取文件的文件名
file.getName();
获取文件的父文件路径
file.getParent();
获取文件的长度(字节数)
file.length();
获取文件所在盘符的剩余字节大小
file.getFreeSpace();
获取文件所在盘符的总大小
file.getTotalSpace();
获取文件所在盘符的可用空间
file.getUsableSpace();
是否是可执行文件
file.canExecute()
是否可读
file.canRead();
是否可写
file.canWrite();
文件最后一次修改的时间
file.lastModified();
//返回long型
long time = file.lastModified();
Date date = new Date(time);
是否是隐藏文件
file.isHidden();
获取文件中的子文件
File[] files = file.listFile();
获取当前操作系统的所有盘符
File[] disks = File.listRoots();
删除文件
可以用于文件和文件夹,如果是文件夹,并且该文件夹有子文件,则不能删除,要删除必须清空文件夹的子文件
file.delete()
操作
查看所有文件的方法
/**
* 查看所有文件的方法
*/
public void showFiles(String path){
//根据路径获得文件
File file = new File(path);
//判断文件是否存在
if(file.exists()){
System.out.println(file.getAbsolutePath());
//判断是否是文件夹
if(file.isDirectory()){
//如果是文件夹,则获取文件夹中的子文件
File[] files = file.listFiles();
if(files != null){
//遍历子文件
for(File childFile : files){
//递归查看
showFiles(childFile.getAbsolutePath());
}
}
}
- }
- }
根据文件类型查找显示文件
/**
* 根据文件类型查找显示文件
* @param path
* @param type
*/
public void showFiles(String path, String type){
//根据路径获得文件
File file = new File(path);
//判断文件是否存在
if(file.exists()){
//判断文件是否是文件
if(file.isFile()){
//如果是文件就要判断文件的后缀名是否和查找的文件类型匹配
if(validateFile(file.getName())){
//获取文件的后缀名
String fileType = file.getName().substring(file.getName().lastIndexOf(".")+1);
//判断后缀名是否和查找文件匹配
if(fileType.equalsIgnoreCase(type)){
//打印显示文件
System.out.println(file.getAbsolutePath());
}
}
}
//如果是文件夹递归查找
else{
//如果是文件夹,则获取文件夹中的子文件
File[] files = file.listFiles();
if(files != null){
//遍历子文件
for(File childFile : files){
//递归查看
showFiles(childFile.getAbsolutePath(),type);
}
}
}
}
}
/**
* 验证文件是否是一个合法文件
* @return
*/
public boolean validateFile(String fileName){
if(fileName.indexOf(".") != -1){
return true;
}
return false;
}
创建单个文件的方法
/**
* 创建单个文件的方法
* @param fileName 新建的文件名
* @param path 创建的位置
*/
public void createFile(String fileName, String path){
//根据父文件路径创建File对象
File parentFile = new File(path);
//判断父文件是否存在
if(parentFile.exists()){
//判断父文件是否是文件夹
if(parentFile.isDirectory()){
//构建File对象
File file = new File(path, fileName);
//判断要新建的文件是否存在
if(!file.exists()){
//创建
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(null, "该文件已经存在!");
}
}
}
else{
JOptionPane.showMessageDialog(null, "文件夹不存在!");
}
}
创建文件夹的方法
/**
* 创建文件夹的方法
*/
public void createDirectory(String fileName, String path){
//new File("").mkdir();
}
/**
* 对文件进行重命名的方法
* @param source 要修改的源文件路径
* @param fileName 文件的新命名(不包含后缀名)
*/
public void reNameFile(String source, String fileName){
File sourceFile = new File(source);
//判断源文件是否存在
if(sourceFile.exists()){
//判断源文件是否有后缀名
if(validateFile(sourceFile.getName())){
//获取源文件的后缀名
String type = sourceFile.getName().substring(sourceFile.getName().lastIndexOf("."));
//根据源文件的路径以及后缀名创建新命名的文件对象
File file = new File(sourceFile.getParent(),fileName+type);
判断新的文件名是否存在
if(!file.exists()){
//重命名
sourceFile.renameTo(file);
}
}
}
}
删除文件的方法
/**
* 删除文件的方法
*/
public void deleteFile(String path){
File file = new File(path);
// //删除文件,可以用于文件和文件夹
// //如果是文件夹,并且该文件夹中有子文件,则不能删除
// //如有以上情况则必须清空文件夹中的子文件
// file.delete();
//判断文件是否存在
if(file.exists()){
//判断文件是否是文件夹
if(file.isDirectory()){
//如果是文件夹获取子文件
File[] files = file.listFiles();
if(files != null){
//递归删除
for(File childFile : files){
deleteFile(childFile.getAbsolutePath());
}
}
}
//无论是否是文件夹都应删除当前文件
file.delete();
}
}
IO流
InputStream 所有输入流的基类 是一个抽象类
OutputStream 所有输出流的基类 也是一个抽象类
常用的实现类
FileInputStream FileOutputStream
BufferedInputStream BufferedOutputStream
需要通过抽象的实例类才能对文件进行流的读写
读写
通过输入流的read方法读取文件流的字节信息
将每次读取到的信息通过输出流写入到新的文件中
int data;
while((data = input.read()) != -1){
output.write(data);
}
JAVA中IO流的分类
1、字节流
以单字节的方式进行读取
2、字符流
以单字符的方式进行读取
字符流在读取文本信息时效率高于字节流
字符流由字节流衍生而来,因此必须借助于字节流实现
字符流不能对单字节构成的文件进行读写,如视频图片
字符流
Reader 字符输入流的基类 抽象类
Writer 字符输出类的基类 抽象类
InputStreamReader OutputStreamWriter
BufferedReader BufferedWriter
1、使用字节流读写文件中的字节数据
//数据流不能对文件夹进行读写
FileInputStream fis = new FileInputStream(new File("d:/a.txt"));
//每次读取一个字节,因此通过循环反复读取字节
int data;
while((data = fis.read()) != -1){
system.out.println(data);
}
fis.close();
2、使用输出流将字节数据写入文件
//创建输出流的时候如果文件不存在,则会自动创建文件,如果文件存在则将默认覆盖文件
//第二个参数表示是否追加数据,默认为false
FileOutputStream fos = new FileOutputStream(new File("d:/b.txt"),true);
//写入数据
fos.write(66);
fos.write(67);
//清空缓冲流
fos.flush();
fos.close();
(优)3、使用缓冲流优化
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("d:/flash.exe")));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("d:/test.exe")));
int len;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
bos.write(buffer, 0, len);
}
bis.close();
bos.flush();
bos.close();
(优)4、自定义缓冲流
FileInputStream fis = new FileInputStream(new File("d:/flash.exe"));
FileOutputStream fos = new FileOutputStream(new File("d:/test.exe"));
//读取长度
int len;
//缓冲数组
byte[] buffer = new byte[1024];
//每次读取都将字节写入缓冲区
while((len = fis.read(buffer)) != -1){
//将缓冲区中的数据写入文件
fos.write(buffer,0,len);
}
fis.close();
fos.flush();
fos.close();
字符流
字符流只适合读取纯文本的File文件,字符流的构建依赖于字节流
使用字符流读写文本
try {
InputStreamReader reader = new InputStreamReader(new FileInputStream(new File("d:/a.txt")));
char[] buffer = new char[1024];
StringBuffer str = new StringBuffer();
int len;
while((len = reader.read(buffer)) != -1){
str.append(buffer);
}
reader.close();
System.out.println(str);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
使用字符缓冲流
InputStreamReader是字节流到字符缓冲流的桥梁
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:/a.txt"))));
String s;
//一次读取一行
while((s = reader.readLine()) != null){
System.out.println(s);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("d:/b.txt"))));
//使用输出流写入数据
writer.write("这是我新建的文本\r\n");
//换行
//writer.newLine();
writer.write("又一段新的内容");
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
自定义键盘接受
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
序列化 及 反序列化 ObjectInputStream ObjectOutputStream
序列化的对象要使用
Serializable接口
import java.io.Serializable;
public class User implements Serializable{
private int userId;
private String name;
public User(int userId, String name) {
super();
this.userId = userId;
this.name = name;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
添加两个实例对象(user)到 list 集合里
User user1 = new User(1001, "tom");
User user2 = new User(1002, "jack");
ArrayList<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
进行序列化保存
try {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(new File("d:/users.data")));
//将对象通过输出流进行序列化保存
//序列化对象必须实现序列化接口
output.writeObject(list);
output.flush();
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
反序列化读取文件
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(new File("d:/users.data")));
ArrayList<User> list = (ArrayList<User>) input.readObject();
input.close();
for(User user : list){
System.out.println(user.getUserId()+"\t"+user.getName());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}