IO流第31天(文件流,创建文件的3种方式,获取文件的相关信息)
IO流
文件
文件是保存数据的地方,例如Word文档,Excel文件等,既可以保存图片,也可以保存视频,声音等
文件流
文件在程序中是以流的形式来操作的
创建文件
- new File(String pathname)//根据路径构造一个file对象
- new File(File parent,String child)//根据父目录文件+子路径构建
- new File(String parent,String child)//根据父目录+子路径构建
第一个方法是直接指定路径创建文件,第二种是根据已知文件名创建新文件在那已知的目录上,第三种是通过路径,通过已知旧文件路径创建
creatNewFile()方法创建新文件
//方式一 new File(String pathname)根据路径构造一个file对象
@Test
public void create01(){
String filePath="d:\\news1.txt";
File file = new File(filePath);//此处的file对象在java程序中只是一个对象
try {
file.createNewFile();//执行了createNewFile()方法才会真正在磁盘创建该文件
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式二new File(File parent,String child)//根据父目录文件+子路径构建
@Test
public void create02(){
//e:\\new2.txt
File parentFile = new File("d:\\");
//String parentFile="d:\\";
String fileName="news2.txt";
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件news2创建成");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式三:new File(String parent,String child)//根据父目录+子路径构建
@Test
public void create03()
{
String parentPath="d:\\";
String filePath="news3.txt";
File file = new File(parentPath, filePath);
try {
file.createNewFile();
System.out.println("文件news3创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
获取文件相关信息
方法名 | 方法作用 |
---|---|
getName() | 获取文件名 |
getAbsolutePath() | 获取文件路径 |
getParent() | 获取父级目录 |
length() | 获取文件长度(按字节统计,一个英文字母一个字节,一个汉字3个字节) |
exists() | 判断该文件是否存在(True/False) |
isFile() | 判断是否为文件(True/False) |
isDirectory() | 判断是否为目录(True/False) |
//先创建文件对象
File file = new File("d:\\news1.txt");
//调用相应的方法得到对应信息
System.out.println("文件名=="+file.getName());
System.out.println("文件绝对路径=="+file.getAbsolutePath());
System.out.println("文件父级目录=="+file.getParent());
System.out.println("文件大小(按字节统计)=="+file.length());//一个英文字母一个字节,一个汉字3个字节
System.out.println("文件是否存在=="+file.exists());
System.out.println("是否是文件=="+file.isFile());
System.out.println("是不是目录=="+file.isDirectory());
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?