打印目录结构:调用showDir方法,并传递两个参数进去,其中一个用于控制显示"-"的数目以显示层次结构,另外一个参数传递目录路径。通过getName()获取文件名,listFiles()获取所有文件和目录的路径,并通过isDirectory()判断是否是文件夹,则打印。
public static void main(String[] args) {
showDir(1, new File("E:\\Hello"));
}
private static void showDir(int indent, File file) {
for (int i = 0; i < indent; i++) {
System.out.print("-");
}
System.out.println(file.getName());
if (file.isDirectory()) {
File[] fs = file.listFiles();
for (int i = 0; i < fs.length; i++) {
showDir(indent + 4, fs[i]);
}
}
}
遍历指定目录下的所有目录:使用File类的list方法。
public static void main(String[] args) {
String path = "E:\\Hello";
File file = new File(path);
File[] flf = file.listFiles();
for (File f : flf) {
if (!f.isDirectory()) {
System.out.println(f);
}
}
}
在指定目录中查找文件示例:
public static void main(String[] args) {
File f = new File("E:\\Hello");
String[] s = f.list();
if(s == null){
System.out.println("该目录不存在");
}else{
for (int i = 0; i < s.length; i++) {
String filename = s[i];
System.out.println(filename);
}
}
}
查看系统跟目录:使用File类的listRoots()方法。该功能不需要任何参数,此方法不会引发任何异常。
public static void main(String[] args) {
File[] roots = File.listRoots();
System.out.println("系统所有根目录:");
for (int i = 0; i < roots.length; i++) {
System.out.println(roots[i].toString());
}
}
查看当前工作目录:使用System的getProperty()方法。getProperty()方法是返回由参数表示的系统属性。
public static void main(String[] args) {
String s = System.getProperty("user.dir");
System.out.println("你当前的工作目录为 :" + s);
}
异常处理方法:使用System类的System.err.println()。System.err.println()只能在屏幕上打印。
public static void main(String[] args) {
try {
throw new Exception("我的异常");
} catch (Exception e) {
System.err.println("捕获异常");
System.err.println("获取消息:" + e.getMessage());
e.printStackTrace();
}
}
多个异常处理:对方声明几个异常,就对应几个catch块,在处理异常的时候,一定要把异常范围小的放在前面,范围大的放在后面。
public void doing() throws IOException {
System.out.println("在干嘛");
}
public static void main(String[] args) {
Test1 test = new Test1();
try {
test.doing();
} catch (IOException e) {
} catch (Exception e) {
}
}
Finally的用法:finally块中定义的代码,总是在try和任何catch块之后、方法完成之前运行,被finally控制的语句体一定会执行。
public static void main(String[] args) {
try {
System.out.println(10 / 0);
} catch (Exception e) {
System.out.println("除数为零了");
} finally {
System.out.println("是否执行了");
}
}
使用catch处理异常:try后是正常执行的语句,而catch后是对异常处理的语句,catch的括号中是程序需要处理的异常类型。
public static void main(String[] args) {
int result = 10 / 0;
try {
System.out.println(result);
} catch (Exception e) {
System.out.println("抛出异常:" + e.getMessage());
}
}
多线程异常处理:在主线程中抛出异常,程序停止继续运行,很容易发现;在子线程中抛出异常,主线程会继续执行,很难发现。
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程启动");
Thread thread = new Thread(new Work());
thread.start();
Thread.sleep(1000);
System.out.println("主线程继续执行任务");
}
class Work implements Runnable {
@Override
public void run() {
System.out.println("子线程:" + Thread.currentThread().getName());
throw new RuntimeException();
}
}