File类的使用
查看API文档: File 实现了 Serializable 序列化接口.
序列化作用:
• 提供一种简单又可扩展的对象保存恢复机制。
• 对于远程调用,能方便对对象进行编码和解码,就像实现对象直接传输。
• 可以将对象持久化到介质中,就像实现对象直接存储。
• 允许对象自定义外部存储的格式。
File类只用于表示文件(目录)的信息(名称、大小等),不用于文件内容的访问
package com.java.entity;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Io {
/**
* 程序主入口
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 创建文件
File file = new File("D:/JAVA/por/day07/index.txt");
boolean newFile;
if (file.createNewFile()) newFile = true;
else newFile = false;
System.out.println(newFile);
// 手动创建文件
Scanner scanner = new Scanner(System.in);
System.out.println("请输入文件名:");
String fileName = scanner.next();
File file1 = new File("D:/JAVA/por/day07/" + fileName);//自己任意选择创建文件地址
if (!file1.exists()) {//在创建文件之前判断文件是否存在
boolean newFile1 = file1.createNewFile();
if (newFile1) {
System.out.println("创建成功");
} else {
System.out.println("创建失败");
}
} else {
System.out.println("文件创建已存在");
}
//拿到文件名后缀, 文件名称 ,文件大小
String name = file.getName();
System.out.println(name);
String[] split =name.split("\\.");
String s =split[split.length-1];
System.out.println(s);//获取后缀名
}
}