创建文件
public static void createNewFile() throws IOException {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
f.createNewFile();
}
删除文件
public static void deleteFile() {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
if (f.exists()) {
f.delete();
}
}
新建文件夹
public static void createNewDir() {
String fileName = "F:" + File.separator + "ff";
File f = new File(fileName);
f.mkdir();
}
递归遍历目录
public static void traversalDir(String filePath) {
File dir = new File(filePath);
File[] files = dir.listFiles();
for (File file : files) {
if (file != null) {
if (file.isDirectory()) {
traversalDir(file.getAbsolutePath());
} else {
System.out.println(file.getAbsolutePath());
}
}
}
}
写入文件
public static void writeString2File() throws IOException {
String filePath = "D:" + File.separator + "hello.txt";
File f = new File(filePath);
OutputStream out = new FileOutputStream(f, false);
String str = "abcdefghijklmnopqs";
byte[] bytes = str.getBytes();
for (int i = 0; i < bytes.length; i++) {
out.write(bytes[i]);
}
out.close();
}
读文件
public static void readFile() throws IOException {
String filePath = "D:" + File.separator + "hello.txt";
File f = new File(filePath);
InputStream in = new FileInputStream(f);
byte[] bytes = new byte[1024];
int temp = 0;
int count = 0;
while ((temp = in.read()) != -1) {
bytes[count++] = (byte) temp;
}
in.close();
System.out.println(new String(bytes));
}
对象序列化
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private transient int id = 123;
private transient String name = "abc";
private String password = "12345";
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public User() {
}
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private void privateMethod() {
System.out.println("access the private method");
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
public static void serializClass() throws Exception {
String filePath = "D:" + File.separator + "seri.txt";
File f = new File(filePath);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(new User(123,"jim","abcde"));
out.close();
}
反序列化
public static void deserializClass() throws Exception {
String filePath = "D:" + File.separator + "seri.txt";
File f = new File(filePath);
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
User user = (User) in.readObject();
in.close();
System.out.println(user);
}