Java 文件创建练习

|--需求说明

|--实现思路

1、采用java.io.File类,写两个方法,一个用来创建文件,一个用来获取文件信息

2、实例化方法类,创建文件后,获取文件信息

|--代码内容 

 1 package com.io;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 /**
 7  * @auther::9527
 8  * @Description: 文件操作
 9  * @program: shi_yong
10  * @create: 2019-07-31 14:11
11  */
12 public class Test1 {
13     //创建文件的方法
14     public void creatFile(File file) {
15         if (file.exists()) {
16             System.out.println("文件已存在");
17         } else {
18             try {
19                 file.createNewFile();
20             } catch (IOException e) {
21                 e.printStackTrace();
22             }
23             System.out.println("文件创建成功");
24         }
25     }
26 
27     //删除文件的方法
28     public void deleteFile(File file) {
29         if (file.exists()) {
30             file.delete();
31             System.out.println("文件删除成功");
32         } else {
33             System.out.println("文件不存在,可以不删除");
34         }
35     }
36 
37     //展示文件信息的方法
38     public void showFile(File file) {
39         if (file.exists()) {
40             if (file.isFile()) {
41                 System.out.println("文件名" + file.getName());
42                 System.out.println("文件的相对路径是:"+file.getPath());
43                 System.out.println("文件的绝对路径是:" + file.getAbsolutePath());
44                 System.out.println("文件大小为" + file.length() + "字节");
45             }else if (file.isDirectory()){
46                 System.out.println("这是个目录");
47             }
48 
49         } else {
50             System.out.println("没有找到这个文件");
51         }
52     }
53 
54     //程序入口
55     public static void main(String[] args) {
56         File file = new File("d:/ak.txt");
57         Test1 test1 = new Test1();
58         //文件已存在,我先删除后重新创建
59         test1.deleteFile(file);
60         //重新创建这个文件
61         test1.creatFile(file);
62         //获取文件信息
63         test1.showFile(file);
64 
65     }
66 }
文件创建方法及程序入口

|--运行结果

猜你喜欢

转载自www.cnblogs.com/twuxian/p/11276134.html