资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Java中File类的使用

本篇内容主要讲解“Java中File类的使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java中File类的使用”吧!

鲁甸网站制作公司哪家好,找创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站建设等网站项目制作,到程序开发,运营维护。创新互联公司自2013年起到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联公司

File类的作用

●创建、删除文件;
●重命名文件;
●判断文件的读写权限及是否存在;
●设置和查询文件的最近修改时间等;
●构造文件流可以使用File类的对象作为参数。

创建文件Hello.txt,如果存在则删除旧文件,不存在则直接创建新的

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类的使用”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


名称栏目:Java中File类的使用
转载来于:http://cdkjz.cn/article/gjoegs.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220