review23

文件的创建与删除

当使用File类创建一个文件对象后,例如

File file = new File("C:\myletter", "letter.txt");

如果目录中没有名字为letter.txt文件,文件对象file调用方法

public boolean createNewFile();

删除文件用方法file.delete

代码展示如下所示:

import java.io.File;
import java.io.IOException;

public class Test03 {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        File file = new File("E:/test", "xiaoming.txt");
        if(!file.exists())
        {
            file.createNewFile();
        }
    }

}

在使用createNewFile()方法时,记住要抛出异常,否则会报错。

在路径E:/下本来没有"xiaoming.txt",代码运行后,“xiaoming.txt”文件被创建。

运行可执行文件

当要执行一个本地机器上的可执行文件时,可以使用java.lang包中的Runtime类。首先使用Runtime类声明一个对象,如:

Runtime rc;

然后使用该类的getRuntime()静态方法创建这个对象:

rc = Runtime.getRuntime();

rc可以调用exec(String command)方法打开本地机器上的可执行文件或执行一个操作。

代码展示如下所示:

 1 import java.io.File;
 2 
 3 public class Test04 {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         try{
 8             Runtime rt = Runtime.getRuntime();
 9             File file = new File("D:/eclipse", "eclipse.exe");
10             rt.exec(file.getAbsolutePath());
11             rt.exec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe");
12             File file1 = new File("C:/Program Files (x86)/Google/Chrome/Application",
13                     "chrome www.nwsuaf.edu.cn");
14             rt.exec(file1.getAbsolutePath());
15             File file2 = new File("C:/Program Files/Internet Explorer","IEXPLORE www.baidu.com");
16             rt.exec(file2.getAbsolutePath());
17         }
18         catch(Exception e){}
19     }
20 
21 }

代码运行后,第10条代码是打开eclipse,第11条代码时打开谷歌浏览器,第13条代码时用谷歌浏览器打开特定网址,第16条语句是用默认浏览器打开百度网址。

File file1 = new File("C:/Program Files (x86)/Google/Chrome/Application","chrome www.nwsuaf.edu.cn");
写代码的时候要注意,网址前面需要加上浏览器的名字

原文地址:https://www.cnblogs.com/liaoxiaolao/p/9451188.html