您的位置:首页 > 编程语言 > Java开发

java-I/O File类(1)-createNewFile()-mkdir()-跨平台的绝对路径-delete()-list()-deleteOnExit()

2015-05-04 22:21 1006 查看

File类

创建一个文件 ,一个File类的对象,表示了磁盘上的文件或目录。

[code]class FileTest {
    public static void main(String[] args) throws IOException{
        File f = new File("1.txt");
        //创建一个文件
        f.createNewFile();
    }
}




在eclipse工程目录下新建一个文件成功

创建一个目录

[code]class FileTest {
    public static void main(String[] args) throws IOException{
        File f = new File("1.txt");
        //f.createNewFile();
        //创建目录
        f.mkdir();
    }
}


结果:




创建文件成功

如果想在指定的绝对路径创建文件,在File类构造函数时注意

根据window系统的绝对路径创建文件

注意转义字符

[code]class FileTest {
    public static void main(String[] args) throws IOException{
        //绝对路径创建文件,本意是'\'作为目录的分隔符,在windows系统要在'\'加一个'\'
        File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
        f.createNewFile();
    }
}


结果在指定路径生成了1.txt文件

问题引出:因为在linux目录分隔符是正斜杠’/’程序移植到linux平台就不会识别目录分隔符了,我们要写一个跨平台的绝对路径,File类提供了与平台无关的方法来对磁盘上的文件或目录进行操作。




区别是返回值类型不同

[code]class FileTest {
    public static void main(String[] args) throws IOException{
        //File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");

        //代表盘符根目录
        String strDir = File.separator;
        String strFile = "eclipse workplace" + strDir + "FileTest" + strDir + "1.txt";
        File f = new File(strDir,strFile);
        f.createNewFile();
    }
}


删除文件或者目录

f.delete();

在程序退出时删除文件,用于删除程序运行时的文件

deleteOnExit()

创建临时文件并删除临时文件

[code]class FileTest {
    public static void main(String[] args) throws IOException, InterruptedException{
        File f = File.createTempFile("zfdsfdsd", ".tmp");
        f.deleteOnExit();
        Thread.sleep(3000);
    }
}


列出目录或文件中的所有子文件

[code]class FileTest {
    public static void main(String[] args) throws IOException, InterruptedException{
        String strDir = File.separator;
        //File f = new File("D:\\eclipse workplace\\FileTest\\1.txt");
        String strAdd = "eclipse workplace" + strDir + "FileTest";
        File f = new File(strDir,strAdd);
        f.createNewFile();
        String[] names = f.list();
        for(int i=0;i< names.length;i++){
            System.out.println(names[i]);
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: