Java_IO
一.创建文件的三种方法
1.new File(String pathname)//根据路径构建一个File对象
1 @Test
2 public void create1(){
3 String filePath = "D:\\file1.txt";
4 File file = new File(filePath);
5
6 try{
7 file.createNewFile();
8 System.out.println("创建文件1成功");
9 }catch (IOException e){
10 e.printStackTrace();
11 }
12 }
2.new File(File parent,String child)//根据父目录文件+子路径构建
1 @Test
2 public void create2(){
3 File parentFile = new File("D:\\");
4 String fileName = "file2.txt";
5 File file = new File(parentFile,fileName);
6
7 try{
8 file.createNewFile();
9 System.out.println("创建文件2成功");
10 }catch (IOException e){
11 throw new RuntimeException(e);
12 }
13 }
3.new File(String parent,String child)//根据父目录+子路径构建
1 @Test
2 public void create3(){
3 String parentPath = "d:\\";
4 String filePath = "file3.txt";
5 File file = new File(parentPath,filePath);
6
7 try{
8 file.createNewFile();
9 System.out.println("创建文件3成功");
10 }catch (IOException e){
11 throw new RuntimeException(e);
12 }
13 }
二.文件信息的查询操作
1 @Test
2 public void Info(){
3 File file = new File("D:\\file1.txt");
4 System.out.println("文件名称"+file.getName());
5 System.out.println("文件绝对路径"+file.getAbsolutePath());
6 System.out.println("文件父目录"+file.getParent());
7 System.out.println("文件大小(字节)"+file.length());
8 System.out.println("文件是否存在"+file.exists());
9 System.out.println("是否是文件"+file.isFile());
10 System.out.println("是否是目录"+file.isDirectory());
11 }
三.文件夹的创建
1 @Test
2 public void fileDeleteD1(){
3 String dirPath = "D:\\test\\dir1,txt";
4 File file = new File(dirPath);
5 if(file.exists()){
6 System.out.println(dirPath+"该目录已经存在");
7 }else{
8 if(file.mkdir()){
9 System.out.println("创建成功");
10 }else{
11 System.out.println("创建失败");
12 }
13 }
14 }
四.Scanner与Println
1 public static void main(String[] args) {
2 Scanner input = new Scanner(System.in);
3 String str = input.next();
4 System.out.println(str);
5 System.out.println("hello world");
6 }
1 public static void main(String[] args) {
2 Scanner input = new Scanner((System.in));
3 System.out.print("请输入一个double类型的数");
4 double d = input.nextDouble();
5 System.out.println(d);
6
7 System.out.print("请输入一个int类型的数");
8 int i = input.nextInt();
9 System.out.println(i);
10
11 System.out.print("请输入一个string类型的数:");
12 String s = input.next();
13 System.out.println(s);
14 }
浙公网安备 33010602011771号