Java File 操作

来源:互联网 发布:3米直尺道路检测数据 编辑:程序博客网 时间:2024/06/10 15:10

1.file类

File类的对象可以代表一个具体的文件路径,在实际代表时,可以使用绝对路径也可以使用相对路径。

 File f1 = new File(“d:\\test\\1.txt”);

 File f2 = new File(“1.txt”);

 File f3 = new File(“e:\\abc”);

这里的f1和f2对象分别代表一个文件,f1是绝对路径,而f2是相对路径,f3则代表一个文件夹,文件夹也是文件路径的一种。

        File f4 = new File(“d:\\test\\”,”1.txt”);

        这样代表的文件路径是:d:\test\1.txt。

 

2.file常用方法

createNewFile()  该方法的作用是创建指定的文件。该方法只能用于创建文件,不能用于创建文件夹,且文件路径中包含的文件夹必须存在。

exists() 测试当前 File 是否存在。  

getAbsolutePath() 返回由该对象表示的文件的绝对路径名。  getCanonicalPath() 返回当前 File 对象的路径名的规范格式。  getName() 返回表示当前对象的文件名。  

getParent() 返回当前 File 对象路径名的父路径名,如果此名没有父路径则为 null。  getPath() 返回表示当前对象的路径名。  hashCode() 计算此文件的一个哈希码。  

isFile方法 该方法的作用是判断当前File对象是否是文件。

mkdirs() 创建一个目录,它的路径名由当前 File 对象指定,包括任一必须的父路径。  renameTo(File) 将当前 File 对象指定的文件更名为给定参数 File 指定的路径名。  toString() 返回当前对象的字符串表示.

 

3.读取文件

 

 1).利用FileInputStream读取文件
    
     public String FileInputStreamDemo(String path) throws IOException...{
         File file=new File(path);
         if(!file.exists()||file.isDirectory())
             throw new FileNotFoundException();
         FileInputStream fis=new FileInputStream(file);
         byte[] buf = new byte[1024];
         StringBuffer sb=new StringBuffer();
         while((fis.read(buf))!=-1)...{
             sb.append(new String(buf));    
             buf=new byte[1024];//重新生成,避免和上次读取的数据重复
         }
         return sb.toString();
     }
2).利用BufferedReader读取

     在IO操作,利用BufferedReader和BufferedWriter效率会更高一点

 

     public String BufferedReaderDemo(String path) throws IOException...{
         File file=new File(path);
         if(!file.exists()||file.isDirectory())
             throw new FileNotFoundException();
         BufferedReader br=new BufferedReader(new FileReader(file));
         String temp=null;
         StringBuffer sb=new StringBuffer();
         temp=br.readLine();
         while(temp!=null)...{
             sb.append(temp+" ");
             temp=br.readLine();
         }
         return sb.toString();
     }

 

3) 写文件

       

          FileOutputStream out = null;
        FileOutputStream outSTr = null;
        BufferedOutputStream Buff=null;
        FileWriter fw = null;
        int count=1000;//写文件行数
        try {
            out = new FileOutputStream(new File("C:/add.txt"));
            long begin = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                out.write("测试java 文件操作\r\n".getBytes());
            }
            out.close();
            long end = System.currentTimeMillis();
            System.out.println("FileOutputStream执行耗时:" + (end - begin) + " 豪秒");

            outSTr = new FileOutputStream(new File("C:/add0.txt"));
             Buff=new BufferedOutputStream(outSTr);
            long begin0 = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                Buff.write("测试java 文件操作\r\n".getBytes());
            }
            Buff.flush();
            Buff.close();
            long end0 = System.currentTimeMillis();
            System.out.println("BufferedOutputStream执行耗时:" + (end0 - begin0) + " 豪秒");


            fw = new FileWriter("C:/add2.txt");
            long begin3 = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                fw.write("测试java 文件操作\r\n");
            }
                        fw.close();
            long end3 = System.currentTimeMillis();
            System.out.println("FileWriter执行耗时:" + (end3 - begin3) + " 豪秒");

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                fw.close();
                Buff.close();
                outSTr.close();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

 

4.通过URL获取file类

        URL url = new URL("http://127.0.0.1:8080/weibo.properties");
        URLConnection conn = url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn
                .getInputStream()));
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            reader.close();
        }

 

根据URL获得file,读取并写成流文件返回

        try

        {

            URL url = new URL(fileUrl);

            URLConnection conn = url.openConnection();

            BufferedInputStream bis=new BufferedInputStream(conn

                .getInputStream());

            byte[] buffer = new byte[1024];

            int length=0;

            while ((length=bis.read(buffer))!= -1) {  

                response.getOutputStream().write(buffer, 0, length); 

            }  

            bis.close();

            response.getOutputStream().close();

        }

        catch (Exception e)

        {

            System.out.println("downloadFileByUrl 出现异常:"+e.toString());

 

        }

 

5.copyFile

 

    public static void  copyFile(File sFile,File tFile)  

    {  

        if(sFile!=null&&sFile.isFile()&&sFile.exists())  

        {  

            String tFilePath=tFile.getAbsolutePath();  

            String sFilePath=sFile.getAbsolutePath();  

            if(tFile.exists())  

            {  

                String bakPath=tFile.getAbsolutePath()+".bak";  

                tFile.renameTo(new File(bakPath));  

            }  

            FileInputStream fis = null;  

            FileOutputStream fos = null;  

            try {  

                File targetFile=new File(tFilePath);  

                targetFile.createNewFile();  

                fis = new FileInputStream(sFilePath);  

                fos = new FileOutputStream(tFilePath);  

                byte[] buffer = new byte[1024];

                int length=0;

                while ((length=fis.read(buffer))!= -1) {  

                    fos.write(buffer, 0, length); 

                }  

                fis.close();  

                fos.close();  

            } catch (Exception e) {  

                e.printStackTrace();  

            }  

        }  

 

    }