IO流(1)
2024-10-16 09:03:08
IO流(1)
目录
文件
文件流
文件在程序中以流的形式来操作
输入流:数据从数据源(文件)到程序(内存)的路径
输出流:数据从程序(内存)到数据源(文件)的路径
创建文件
//方法1:new File(String pathname) 根据路径构建一个File对象
public void create1(){
String filepath = "d:\\news1.txt";
File file= new File(filepath);
try {
file.createNewFile();
System.out.println("创建成功!");
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建失败");
}
}
//方法2:new File(File parent,String child) 根据父目录文件+子路径构建
public void create2(){
File file = new File("d:\\");
String fileNmae ="news2.txt";
File file1 = new File(file, fileNmae);
try {
file.createNewFile();
System.out.println("创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
//方法3:new File(String parent,String child) 根据父目录+子路径构建
public void cteate3(){
String parentPath="d:\\";
String filepath = "news1.txt";
File file = new File(parentPath,filepath);
try {
file.createNewFile();
System.out.println("创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
获取文件信息
常用方法:
//获取文件信息
public void info(){
//创建文件对象
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());
System.out.println("文件是否存在"+file.exists());
System.out.println("是不是一个文件"+file.isFile());
System.out.println("是不是一个目录"+file.isDirectory());
目录的操作和文件删除
mkdir 创建一级目录
public void m1(){
String directorPath="d:\\hmy";
File file=new File(directorPath);
if(file.exists()){
System.out.println(directorPath+"存在--");
}else {
if (file.mkdir()){
System.out.println(directorPath+"创建成功--"); }else {
System.out.println(directorPath+"创建失败--");
}
}
}mkdirs 创建多级目录
public void m2(){
String directorPath="d:\\hmy\\a";
File file=new File(directorPath);
if(file.exists()){
System.out.println(directorPath+"存在--");
}else {
if (file.mkdirs()){
System.out.println(directorPath+"创建成功--"); }else {
System.out.println(directorPath+"创建失败--");
}
}
}
delete 删除空目录或文件
public void m3(){
String filePath="d:\\news1.txt";
File file=new File(filePath);
if(file.exists()){
if (file.delete()){
System.out.println(filePath+"删除成功--");
}else {
System.out.println(filePath+"删除失败--");
}
}else {
System.out.println("不存在");
}
}
最新文章
- Percona 5.7安装
- box-sizing属性
- 2016HUAS暑假集训训练2 O - Can you find it?
- Mysql操作笔记(持续更新)
- 读书笔记——《图解TCP/IP》(2/4)
- 【转】 从最简单的vector中sort用法到自定义比较函数comp后对结构体排序的sort算法
- hdu 2818 Building Block
- android系统架构图
- 数据结构(脑洞题,BIT):COGS 2394. 比赛
- hdu 2201
- 今天在写powershell脚本中犯的两个错误
- 使用面向 iOS 的本机插件扩展
- BZOJ 1225: [HNOI2001] 求正整数( dfs + 高精度 )
- jqGrid一些操作
- Thinking in Java系列 文档+代码+简评
- java Scanner类注意事项
- SpringJMS解析-JmsTemplate
- Flask Restful服务简单实现
- .net 环境配置
- 前后端分离——token超时刷新策略