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());


浙公网安备 33010602011771号