闲来无事,想做一个小小的即时网络聊天工具,这就涉及到JAVA网络编程。而网络编程又是以一系列的I/O操作为基础的,还会涉及到诸如加密算法、多线程等领域。
此篇文章记述我在学习文件操作时所练代码,代码如下:
import java.io.File;
public class IOTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
//Create file object
File f1 = new File("d:\\test");
File f2 = new File("1.txt");
File f3 = new File("f:\\file.txt");
File f4 = new File ("d:\\","1.txt");
//Create files
try {
boolean b = f3.createNewFile();
}catch(Exception e) {
e.printStackTrace();
}
//Judge if the file exist
System.out.println(f4.exists());
//Get absolute path
System.out.println(f3.getAbsolutePath());
//Get file name
System.out.println(f3.getName());
//Get parent directory
System.out.println(f3.getParent());
//Judge if it is a directory
System.out.println(f1.isDirectory());
//Judge if it is a file
System.out.println(f3.isFile());
//Get file length
System.out.println(f3.length());
//Get all files and directories' names under current directory
String[] s = f1.list();
for (int i = 0; i < s.length; i++){
System.out.println(s[i]);
}
//Get file object
File[] f5 = f1.listFiles();
for (int i = 0; i < f5.length; i++){
System.out.println("f" + f5[i]);
}
//create directory
File f6 = new File("f:\\test\\abc");
boolean b1 = f6.mkdir();
System.out.println(b1);
b1 = f6.mkdirs();
//Rename file
File f7 = new File("f:\\a.txt");
boolean b2 = f3.renameTo(f7);
System.out.println(b2);
//Set read only
f7.setReadOnly();
}
}
下面这部分是文件的名称打印和删除操作,由于无法直接删除一个非空目录,所以删除非空目录需要先删除其目录下的所有子目录,这就涉及到一个递归遍历问题,代码如下:
import java.io.File;
public class AdvanceFileDemo {
/**
* Advanced file operation demo
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File f = new File("f:\\Book");
printAllFile(f);
File f1 = new File("d:\\test");
deleteAll(f1);
}
/**
* print all the directories and files under current directory
* @param f File object
*/
public static void printAllFile (File f) {
//Print current file name
System.out.println(f.getName());
//If it is a directory
if (f.isDirectory()) {
//Get all sub-directories and files
File [] f1 = f.listFiles();
int len = f1.length;
for (int i = 0; i < len; i++) {
printAllFile(f1[i]);
}
}
}
/**
* Delete all files
* @param f File object
*/
public static void deleteAll (File f) {
//If it is a single file
if (f.isFile()) {
f.delete();
} else {
File f1[] = f.listFiles();
int len = f1.length;
//delete sub-files
for (int i = 0; i < len; i++) {
deleteAll(f1[i]);
}
//delete current file
f.delete();
}
}
}