1.File类的使用:
public class FileTest {
public static void main(String[] args) {
// testFileCreate();
// delDir("G:\\test\\myTestFile");
// printFile("G:\\test\\mytest",0);//0为当前目录层级;就只是个计数器,用于递归调用而已
// changeFile("G:\\test\\mytest\\javabook");
// renameNum("G:\\test\\mytest\\javabook");
renameDel("G:\\test\\mytest\\orcalbook", "zh2");
}
//File类的简单使用
private static void testFileCreate() {
//构造器中传的是路径;我这里用的绝对路径
File file = new File("G:\\test\\fileTest.txt");
File file2 = new File("G:\\test\\myTestFile");
if(file2.mkdir()) {
System.out.println("创建成功");
}
if(file.exists()) {
//获取文件名
String name = file.getName();
//获取文件绝对路径
String absolutePath = file.getAbsolutePath();
//获取文件大小long
long size = file.length();
//获取最后修改事件long
long date = file.lastModified();
System.out.println("文件名:"+name);
System.out.println("绝对路径"+absolutePath);
System.out.println("大小:"+size);
System.out.println("日期:"+new Date(date));
System.out.println("上级目录:"+file.getParent());
System.out.println("上级File对象"+file.getParentFile());
}else {
try {
if(file.createNewFile())
{
System.out.println("Ok");
}else {
System.out.println("创建失败");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//删除目录,递归删除
private static void delDir(String path) {
File dir = new File(path);
if(dir.exists()) {
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(File file:files) {
String absoultePath = file.getAbsolutePath();
delDir(absoultePath);
}
}
dir.delete();
}
}
//递归分层打印目录信息 其中level为目录层级
private static void printFile(String path,int level) {
File dir = new File(path);
if(dir.exists()) {
for(int i=0;i<level;i++) {
System.out.print("\t");
}
System.out.println(dir.getName());
if(dir.isDirectory()) {
File[] files = dir.listFiles();
if(files!=null) {
level++;
}
for(File file:files) {
String absoultePath = file.getAbsolutePath();
printFile(absoultePath,level);
}
}
}
}
/**
以下几个功能是为了:
编写程序将如下目录的文件或子文件进行重命名操作。
books
javabook
1 abczhiliaotang.txt
2 zhiliaotangbcd.txt
10 abczhiliaotang.txt
...
100 abczhiliaotang.txt
dbbook
1 abczhiliaotang.txt
2 zhiliaotangbcd.txt
10 abczhiliaotang.txt
99 abczhiliaotang.txt
1 abc.txt
books目录下的文件名为:
books
javabook
001 abc.txt
002 bcd.txt
010 abc.txt
...
100 abc.txt
dbbook
01 abc.txt
02 bcd.txt
10 abc.txt
99 abc.txt
*/
//获取文件名编号最大长度
private static int getCount(String path) {
File dir = new File(path);
int count = 1;
if(dir.exists()) {
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(File file : files) {
String name = file.getName();
// System.out.println(name);
int temp = 0;
for(int i=0;i<name.length();i++) {
if(name.charAt(i)>=48&&name.charAt(i)<=57) {
temp++;
if(count<temp) {
count = temp;
}
}else {
break;
}
}
}
}
}
// System.out.println(count);
return count;
}
// 对文件编号格式化如从1.txt格式化为01.txt,从2.txt格式化为02.txt
public static void renameNum(String path) {
File dir = new File(path);
File newFile;
int count = getCount(path);
System.out.println("上级"+path);
if(dir.exists()) {
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(File file : files) {
String name = file.getName();
System.out.println(name);
int temp = 0;
for(int i=0;i<name.length();i++) {
if(name.charAt(i)>=48&&name.charAt(i)<=57) {
temp++;
}else {
break;
}
}
for(int i=0;i<count-temp;i++) {
name = "0"+name;
}
String newPath = path+"\\"+name;
System.out.println(newPath);
newFile = new File(newPath);
file.renameTo(newFile);
}
}
}
}
//删除文件名中的指定字符串,对文件进行重命名
public static void renameDel(String path,String str) {
File newFile;
File dir = new File(path);
if(dir.exists()) {
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(File file : files) {
String newName =path+"\\"+file.getName().replace(str, "");
System.out.println("更改后:"+newName);
newFile = new File(newName);
file.renameTo(newFile);
}
}
}
}
}
2.流的操作:
public static void main(String[] args) {
System.out.println("OK");
//copyFile("G:\\test\\mytest\\javabook\\test.png", "G:\\test\\test.png");//文件复制
//testFileOutStreamAndOutStreamWriter();//OutStreamWriter的使用
//testFileWriter();//测试使用FileWriter
//testBufferedWriter();//测试BufferedWriter
try {
testBufferedReader();//测试BufferedReader
testFileReader();测试FileReader
testInputStreamReader();//测试InputStreamReader
} catch (IOException e) {
e.printStackTrace();
}
}
//文件复制功能
private static void copyFile(String org,String des){
try {
InputStream in = new FileInputStream(org);
OutputStream out = new FileOutputStream(des);
byte[] bytes =new byte[1024];
int len=-1;
while ((len=in.read(bytes))!=-1){
out.write(bytes, 0, len);
}
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//OutputStreamWriter的使用
private static void testFileOutStreamAndOutStreamWriter(){
try {
OutputStream outputStream = new FileOutputStream("G:\\test\\mytest\\javabook\\testFileIO.txt");
Writer writer = new OutputStreamWriter(outputStream);
writer.write("嘿嘿嘿");
writer.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//FileWriter的使用
private static void testFileWriter(){
try{
//创建类的实例
Writer writer = new FileWriter("G:\\test\\mytest\\javabook\\book1.txt");
//写入数据
writer.write("Hello 中国");
//关闭流
writer.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
//bufferedWriter的使用
private static void testBufferedWriter(){
try{
/*
//创建类的实例
Writer writer = new FileWriter("book.txt");
//创建BufferedWriter类的实例
BufferedWriter bufferedWriter = new BufferedWriter(writer);
*/
//创建BufferedWriter类的实例
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("G:\\test\\mytest\\javabook\\book2.txt"));
//写入数据
bufferedWriter.write("Hello 中国");
//写入换行符
bufferedWriter.newLine();
//写入数据
bufferedWriter.write("Hello 中国");
//关闭流
bufferedWriter.close();
bufferedWriter.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
//BufferedReader的使用
private static void testBufferedReader()throws IOException{
//创建字符流类的实例
Reader reader = new FileReader("G:\\test\\mytest\\javabook\\book2.txt");
//创建BufferedReader类的实例
BufferedReader bufferedReader = new BufferedReader(reader);
//一行内容
String line = null;
while((line = bufferedReader.readLine())!=null){
//打印一行
System.out.println(line);
}
//关闭流
bufferedReader.close();
reader.close();
}
//FileReader的使用
private static void testFileReader()throws IOException{
//创建字符流类的实例
Reader reader = new FileReader("G:\\test\\mytest\\javabook\\book2.txt");
//缓冲区
char[] buffer = new char[1024];
int len = -1; //读取字符的长度
//读取数据
while((len = reader.read(buffer))!=-1){
//使用字符数组构造字符串对象
String content = new String(buffer);
//打印
System.out.println(content);
}
//关闭流
reader.close();
}
//InputStreamReader的使用
private static void testInputStreamReader()throws IOException{
//创建字节流类的实例
InputStream in = new FileInputStream("G:\\test\\mytest\\javabook\\book2.txt");
//创建字符流类的实例
Reader reader = new InputStreamReader(in);
//缓冲区
char[] buffer = new char[1024];
int len = -1; //读取字符的长度
//读取数据
while((len = reader.read(buffer))!=-1){
//使用字符数组构造字符串对象
String content = new String(buffer);
//打印
System.out.println(content);
}
//关闭流
reader.close();
in.close();
}
3.序列化与反序列化案例:
序列化:将对象存入文件的过程。
反序列化:读取文件中存储的对象。
两个类:ObjectInputStream类和ObjectOutoptStream
首先创建一个类,实现Serializable接口
1.普通对象序列化与反序列化
public class Emp implements Serializable{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Emp(int id, String name) {
super();
this.id = id;
this.name = name;
}
}
使用ObjectOutputStream(OutStream out)进行序列化
主要使用writeObject(Object obj)方法
//序列化
private static void testObjectOutputStream(Emp emp) {
try {
//我写死了路径,一般路径是作为参数传入的
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\TestJava\\testObjectIO.txt"));
oos.writeObject(emp);
oos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
使用ObjectInputStream(InputStream in)进行反序列化
使用 readObject().进行读取,强制转换
//反序列化
private static void testObjectInputStream() {
try {
//我写死了路径,一般路径是作为参数传入的
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\TestJava\\testObjectIO.txt"));
Emp emp = (Emp)ois.readObject();
System.out.println(emp.getName());
//修改name属性
emp.setName("lisi");
//调用上面的方法,重新序列化
testObjectOutputStream(emp);
ois.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2.集合与反序列化:
//准备工作:
public static void main(String[] args) {
// copyFile("G:\\test\\mytest\\javabook\\test.png", "G:\\test\\test.png");
//testObjectIO();
Emp emp1 = new Emp(1, "张三");
Emp emp2 = new Emp(2, "李四");
Emp emp3 = new Emp(3, "张5");
List<Emp> emps = new ArrayList<Emp>();
emps.add(emp1);
emps.add(emp2);
emps.add(emp3);
// testCollectionObjOut(emps);//集合对象序列化存入txt文件
// testObjectIO(emp);//对象序列化存入txt文件
// testObjectIn();//对象反序列化
testCollectionObjIn();//集合对象反序列化
}
//反序列化,写入集合
private static void testCollectionObjOut(List list) {
try {
//我写死了路径,一般路径是作为参数传入的
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\TestJava\\testCollectionObj.txt"));
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//反序列化,从txt文件中读取集合
private static void testCollectionObjIn() {
try {
//我写死了路径,一般路径是作为参数传入的
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\Administrator\\Desktop\\TestJava\\testCollectionObj.txt"));
List<Emp> emps = (List<Emp>) ois.readObject();
for(Emp emp:emps) {
System.out.println(emp);
}
ois.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}