您好,登录后才能下订单哦!
密码登录
            
            
            
            
        登录注册
            
            
            
        点击 登录注册 即表示同意《亿速云用户服务条款》
        本篇内容主要讲解“Java中File类的使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java中File类的使用”吧!
●创建、删除文件;
●重命名文件;
●判断文件的读写权限及是否存在;
●设置和查询文件的最近修改时间等;
●构造文件流可以使用File类的对象作为参数。
import java.io.*;
public class FileTester {
    public static void main(String[] args) {
        File f=new File("Hello.txt");
        if (f.exists()) 
            f.delete();
        else
        try{
            f.createNewFile();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
}运行结果
因为在前面的例子中已经创建了Hello.txt ,所以第一次运行将删除这个文件
第二次运行则又创建了一个此名的空文件
分析
在试图打开文件之前,可以使用File类的isFile方法来确定File对象是否代表一个文件而非目录
还可通过exists方法判断同名文件或路径是否存在,进而采取正确的方法,以免造成误操作
import java.io.*;
class NewCopyBytes{
    public static void main ( String[] args ){
        DataInputStream instr;
        DataOutputStream outstr;
        if( args.length!= 2 ) {
            System.out.println("Please Enter file names!");
            return;
        }
        File inFile = new File( args[0] );
        File outFile = new File( args[1] );
        if( outFile.exists() ) {
            System.out.println( args[1] +"already exists");
            return;
        }
        if ( !inFile.exists()) {
            System.out.println( args[0] +"does not exist");
            return;
        }
        try{
            instr = new DataInputStream(new BufferedInputStream(new FileInputStream(inFile)));
            outstr = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        
            try{
                int data;
                while ( true ) {
                    data = instr.readUnsignedByte(); 
                    outstr.writeByte(data); 
                }
            }
            catch ( EOFException eof ){
                outstr.close(); 
                instr.close(); 
                return;
            }
        }
        catch ( FileNotFoundException nfx ){ 
            System.out.println("Problem opening files" ); 
        }
        catch ( IOException iox )
        { 
            System.out.println("IO Problems" ); 
        }
    }
}到此,相信大家对“Java中File类的使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。