Java异常处理和File基本操作

编译和运行时的异常处理
1.编译异常:
当编译发生异常时系统会强制你去处理 try或者抛出(throw)
2.运行异常(RuntimeException)
1)方法声明上 可以不用throw来表示
2)可以不对运行异常进行处理
3)不处理直接停止程序 处理程序可以继续运行
4)当在方法中抛出运行异常时说明发生该异常 这事需要停止程序 修改代码让程序停下来
1.异常类
class Test{
//  抛出编译异常
    public void fun1() throws Exception{
        throw new Exception();
    }
//  抛出运行时异常
    public void fun2(){
        throw new RuntimeException("运行异常");
    }
    public double getArea(double r){
//      如果半径下等于0 接下去运算将没有意义
//      这时可以抛出 运行异常 来停止程序 修改代码
        if(r <= 0) {
            throw new  RuntimeException("运行时异常");
        }
        return r * r * Math.PI;
    }
}
1.1.测试编译异常
public class Text {
public static void main(String[] args) {
    Test test = new Test();
    try {
        test.fun1();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

}
}
运行结果:
null
java.lang.Exception
    at Test.fun1(Demo01.java:39)
    at Text.main(Text.java:6)


public class Text {
public static void main(String[] args) {
    Test test = new Test();
    try {
        test.fun2();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }

}
}
运行结果:
运行异常
java.lang.RuntimeException: 运行异常
    at Test.fun2(Demo01.java:43)
    at Text.main(Text.java:6)
1.2.测试运行异常
public class Text {
public static void main(String[] args) {
    Test test = new Test();
    double area = test.getArea(0);
    System.out.println(area);

}
}


运行结果:
Exception in thread "main" java.lang.RuntimeException: 运行时异常
    at Test.getArea(Demo01.java:49)
    at Text.main(Text.java:5)
2.继承中的方法重写
1.如果父类没有抛出异常 子类不能抛出异常
2.如果子类重写父类方法中 调用了一个有异常的方法这时只能选择try...catch 处理 不能进行抛出
3.如果父类抛出异常 子类可以抛也可以不抛
3.测试父类继承的方法
class  Father1 {
    public void fun() throws Exception {

    }
}
class Son2 extends Father1{
    @Override
    public void fun() throws Exception {
        try {
        method();

        }catch(Exception e){
        System.out.println("12");
        }

    }
    //带异常的类
    public void method() throws RuntimeException {

    }
}
3.File类简单操作
功能介绍:
1.操作文件
2.操作文件夹
3.操作文件的路径
4.File的静态变量成员变量在不同系统下获取的路径分隔符不同 
Mac系统下 路径的分隔符为:(冒号)
window下 分割符为;(分号)
    String pathseparator = File.pathSeparator;
    System.out.println(pathseparator);
运行结果: :(冒号)
windows 下 ;(分号)
    String separator = File.separator;
    System.out.println(separator);
运行结果: /
windows 下 \;
3.1File类构造方法
 File(String pathname)
 File(String parent, String child)
 File(File parent, String child)
功能1.打印路径
public class Text {
public static void main(String[] args) {
    File  file = new File("/Users/lanou/Desktop/test");
    System.out.println(file);
//  1.判断该了路径是否存在
    boolean b1 = file.exists();
    System.out.println(b1);
//  使用相对路径 参照当前工程根目录
    File file2 = new File("src/wl.txt");
//    打印绝对路径
    System.out.println(file2.getAbsolutePath());

}
}
运行结果:
/Users/lanou/Desktop/test
true
/Users/lanou/Desktop/sh-day--023/src/wl.txt
功能2.拼接路径
public class Text {
public static void main(String[] args) {
    String parent = "/Users/lanou/Desktop/";
    String child = "test";
    File file = new File(parent, child);
    boolean b1 = file.exists();//判断该路径是否存在
    System.out.println(b1);
    System.out.println(file);

}
}
运行结果:
true
/Users/lanou/Desktop/test
功能3.路径中转拼接
public class Text {
public static void main(String[] args) {

String parent = "/Users/lanou/Desktop/";
String child = "test";
File file = new File(parent);
File file2 = new File(file, child);
System.out.println(file2.exists());

}
}
运行结果:
true
4.创建功能
public boolean createNewFile()
public boolean mkdir()
public boolean mkdirs()
功能1.创建文件
1.文件已经存在 不会重新创建 
2.改方法只能创建文件 不给后缀也是创建的文件

public class Text {
public static void main(String[] args) throws IOException {
//创建桌面test文件下创建kkk文件
File file = new File("/Users/lanou/Desktop/test/kkk");
boolean b1 = file.createNewFile();
System.out.println(b1);
//当前路径下创建ddp.txt文件
File file2 = new File("src/ddp.txt");
boolean b2  = file2.createNewFile();
System.out.println(b2);

}
运行结果;
true
true

目标文件创建成功
功能2.创建文件夹
1.makdir()只能创建一级文件夹
2.makdirs()可以创建多级的文件夹(只要没有就会帮你创建)
public class Text {
public static void main(String[] args) throws IOException {
File file = new File("/Users/lanou/Desktop/test/www/sss");
boolean b = file.mkdirs();//创建多层文件夹
File file1 = new File("/Users/lanou/Desktop/test/555");//创建单词文件夹
boolean b2 = file1.mkdir();
System.out.println(b);
System.out.println(b2);
}
}
运行结果:
true
true


目标文件夹创建成功
5.删除功能
public boolean delete()
1.  删除(不能恢复)不走回收站
2.  如果文件夹下没有子文件夹可以删除
public class Text {
public static void main(String[] args) throws IOException {
    File file = new File("/Users/lanou/Desktop/test/555");
    boolean b = file.delete();
    System.out.println(b);
}
}
运行结果:
true
目标文件删除不见
6.判断功能
 public boolean isDirectory()// 判断是否是文件夹
 public boolean isFile()//判断是否是文件
 public boolean exists()//判断文件是否存在
public class Text {
public static void main(String[] args) throws IOException {
    File file = new File("/Users/lanou/Desktop/test/www");
    boolean b = file.isDirectory();判断是否是文件夹
    boolean b1 = file.isFile();判断是否是文件
    System.out.println(b1);
    System.out.println(b);
}
}
运行结果:
false
true
8.获取功能
 public boolean isDirectory()// 判断是否是文件夹
 public boolean isFile()//判断是否是文件
 public boolean exists()//判断文件是否存在
 获取功能
 public String getPath()
 public String getName()
 public long length()
 public String getAbsolutePath()//获取绝对路径以字符串形式
 public File getAbsoluteFile()//获取绝对路径 以文件对象形式

 public File getParentFile()//获取父级路径
 public String getParent()
 public String[] list()//
 public File[] listFiles()//将路径文件当成一个数组
public class Text {
public static void main(String[] args) throws IOException {
//1.获取文件路径(跟tostring一样 输出路径 不管文件夹是否存在)
    File file  = new File("/Users/lanou/Desktop/test/haha.txt");
    String path = file.getPath();
    System.out.println(path);
//2.获取文件名字
    String name = file.getName();
    System.out.println(name);
//3.获取文件夹长度(多少字节)
    //英文占一个字节 中文占3个字节
 long length = file.length();
 System.out.println(length);
 //4.获取父级路径
 File parentFile = file.getParentFile();
 System.out.println(parentFile);
}
}

运行结果::
/Users/lanou/Desktop/test/haha.txt
haha.txt
6
/Users/lanou/Desktop/test
public class Text {
public static void main(String[] args) throws IOException {
     getFileName( new File("/Users/lanou/Desktop/test"));
}
public static void getFileName(File  file) {
     File[] listFiles = file.listFiles();
     for(File file2 : listFiles) {
         if (file2.isFile()){
            System.out.println(file2);
        }else {
            getFileName(file2);
        }
     }
}
}
运行结果:
/Users/lanou/Desktop/test/.DS_Store
/Users/lanou/Desktop/test/haha.txt
/Users/lanou/Desktop/test/kkk
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个很好的实验,让学生们掌握文件和目录的基本操作,以及如何处理异常。下面是一些可能有用的代码示例。 1. 创建目录: ```java File dir = new File("myDir"); if (!dir.exists()) { if (dir.mkdir()) { System.out.println("Directory created successfully!"); } else { System.out.println("Failed to create directory!"); } } ``` 2. 创建文件: ```java File file = new File("myDir/myFile.txt"); if (!file.exists()) { try { if (file.createNewFile()) { System.out.println("File created successfully!"); } else { System.out.println("Failed to create file!"); } } catch (IOException e) { System.out.println("An error occurred while creating the file: " + e.getMessage()); } } ``` 3. 顺序读写: ```java File file = new File("myDir/myFile.txt"); try (FileWriter writer = new FileWriter(file)) { writer.write("Hello, world!"); writer.write("This is a test."); } catch (IOException e) { System.out.println("An error occurred while writing to the file: " + e.getMessage()); } try (FileReader reader = new FileReader(file)) { int c; while ((c = reader.read()) != -1) { System.out.print((char) c); } } catch (IOException e) { System.out.println("An error occurred while reading the file: " + e.getMessage()); } ``` 4. 随机读写: ```java RandomAccessFile file = new RandomAccessFile("myDir/myFile.txt", "rw"); file.seek(5); // move pointer to position 5 file.write("world".getBytes()); // overwrite "world" at position 5 file.seek(0); // move pointer to beginning of file byte[] buffer = new byte[1024]; int bytesRead = file.read(buffer); while (bytesRead != -1) { System.out.print(new String(buffer, 0, bytesRead)); bytesRead = file.read(buffer); } ``` 5. 异常处理: ```java try { File file = new File("myDir/doesNotExist.txt"); FileReader reader = new FileReader(file); // do something with the reader } catch (FileNotFoundException e) { System.out.println("The file does not exist!"); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值