Java文件操作-讀/寫/複製/刪除/隨機訪問

這裏寫圖片描述???一次讀取一行的操作,在運行時控制檯一直在加載,無法輸入數據,不知道爲啥




 1. 創建文件及其文件夾
 2. 刪除文件及其文件夾
 3. 複製文件
 4. 重命名文件
 5. 讀文件
 6. 寫文件
 7. 文件鎖

    public class OnceFile {//創建文件
        public void createFile(String path,String pathName) {
            try {
                File file = new File(path+File.separator+pathName);
                if(!file.exists())
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
            }
    }
    //創建文件夾
    public void createFileDir(String dir){
        File file = new File(dir);
        if (!file.exists()){
            file.mkdir();
        }
    }
    //刪除文件
    public void delFile(String pathName){
        File file = new File(pathName);
        if (file.exists()){
            file.delete();
        }else {
            System.out.println("所刪除的文件不存在!");
        }
    }
    //刪除某個文件夾及其子文件
    public void delFileDir(File file){
        File[] filesList = file.listFiles();
        for (int i = 0; i < filesList.length; i++) {
            if (file.isDirectory()) {
                filesList[i].delete();//刪除file的子文件及其路徑下的文件
            }
        }
        file.delete();
    }

    //列出文件夾下有哪些文件
    public void hasSrc(String path){
        File file = new File(path);
        File[] filesList = file.listFiles();
        System.out.println("--------文件夾下的所有文件及其路徑---------");
        for (File list:filesList){
            System.out.println(list);
        }
        System.out.println("-------系統跟文件下的文件和路徑-------------");
        File[] listRoots = file.listRoots();
        for (File root:listRoots) {
            System.out.println(root);
        }
    }
    //複製文件
    //如果找不到原文件則拋出異常
    public void copyFile(String fileOldName, String fileNewName){
        //創建字節輸入流
        try (FileInputStream fis = new FileInputStream(fileOldName)) {
            //字節輸出流
            FileOutputStream fos = new FileOutputStream(fileNewName);
            byte[] bytes = new byte[1024];
            //定義一個實際存儲的字節數
            int haRead = 0;
            //循環讀取數據
            while ((haRead = fis.read())>0){
                //向新的文件寫入數據
                fos.write(bytes,0,haRead);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
```

  //1、重命名文件名,不可更改文件的擴展名,如果該文件不存在,不報錯
    public void renameFileName(String oldName, String destName){
        if(oldName.isEmpty()){
            File oldFileName = new File(oldName);
            File newFileName = new File(destName);
            boolean b = oldFileName.renameTo(newFileName);
            if (b){
                System.out.println("-------修改成功------");
                System.out.println("新的文件名~~~~~"+newFileName.getName());
            }
        }
    }
    //2、重命名文件名,不可更改文件的擴展名,如果該文件不存在,不報錯
    public void renameFile(File oldName, File destName){
        if(oldName.exists()){
            boolean b =  oldName.renameTo(destName);
            if (b){
                System.out.println("-------修改成功------");
                System.out.println("新的文件名~~~~~"+destName.getName());
            }
        }
    }
    //讀文件
    //FileInputStream讀文件本身
    public void fileInputStreamFile(File file){
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] bytes = new byte[1024];
            int hasRead = 0;
            while ((hasRead = fis.read(bytes))>0){
                System.out.println(new String(bytes,0,hasRead));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //FileReader讀文件本身
    public void fileReadFile(File file){
        try (FileReader fr = new FileReader(file)) {
            //包裝成處理流
            BufferedReader br = new BufferedReader(fr);
            char[] chars = new char[1024];
            int hasRead = 0;
            while ((hasRead = br.read(chars))>0){
                System.out.println(new String(chars,0,hasRead));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   // 文件讀取(內存映射方式).這種方式的效率是最好的,速度也是最快的,因爲程序直接操作的是內存
    @Test
    public void mappedFile(){
        File f=new File("E:"+File.separator+"xz"+File.separator+"pom.txt");
        byte[] b =new byte[(int) f.length()];;
        int len = 0;
        try (FileInputStream in = new FileInputStream(f)) {
            FileChannel chan = in.getChannel();
            MappedByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
            while (buf.hasRemaining()) {
                b[len] = buf.get();
                len++;
                System.out.println(new String(b,0,len));
            }
            chan.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 //寫文件

    //FileWriter寫文件
    public void writeFile(File file){
        try (FileWriter fw = new FileWriter(file)) {
            fw.write("\t靜月思\n\t\t\t--李白\n" );
            fw.write("\t窗前明月光\n");
            fw.write("\t疑似地上霜\n");
            fw.write("\t舉頭望明月\n");
            fw.write("\t低頭思故鄉\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //PrintWriter寫文件本身
    public void printWriterFile(File file){
        try (FileOutputStream fos = new FileOutputStream(file)) {
            PrintStream ps = new PrintStream(file);
            ps.print("哈哈哈,笑什麼笑,不知道爲什麼笑");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
    RandomAccessFile支持對隨機訪問文件的讀取和寫入。
    隨機訪問文件的行爲類似存儲在文件系統中的一個大型 byte 數組。
    存在指向該隱含數組的光標或索引,稱爲文件指針;輸入操作從文件指針開始讀取字節,並隨着對字節的讀取而前移此文件指針。
    如果隨機訪問文件以讀取/寫入模式創建,則輸出操作也可用;輸出操作從文件指針開始寫入字節,並隨着對字節的寫入而前移此文件指針。
    寫入隱含數組的當前末尾之後的輸出操作導致該數組擴展。該文件指針可以通過 getFilePointer 方法讀取,並通過 seek 方法設置。
     */
    //訪問指定中間部分的文件數據
    public void accessRandomFile(String str,String model,long pos){//model表示以什麼形式訪問,pos表示記錄指針的位置
        //創建字節輸入流
        try (RandomAccessFile raf = new RandomAccessFile(str,model)) {
            //移動raf的文件記錄指針的位置,定位到pos字節處
            raf.seek(pos);
            //用來保存實際讀取的字節數
            int hasRead = 0;
            byte[] bytes = new byte[4048];
            //循環讀取文件中的內容
            while ((hasRead = raf.read(bytes))>0){
                System.out.println(new String(bytes,0,hasRead));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 //在指定文件最後追加內容
    //model表示以什麼形式訪問,pos表示記錄指針的位置
    public  void insertContent(File file,String model){
        try (RandomAccessFile raf = new RandomAccessFile(file,model)) {
            raf.seek(raf.length());
            String content = "追加的內容在此,你怕不怕";
            //每次追加都會在原來的基礎上追加,不會覆蓋
            raf.write(content.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   //向執行文件、指定位置插入內容的功能
    //------原理--------如果需要向指定文件插入內容,程序需要先把插入點後面的內容讀入緩衝區,等把需要
    //--------------插入的數據寫入到文件後,再將緩衝區的內容追加文件後面
    ///model表示以什麼形式訪問,pos表示記錄指針的位置,insertContent爲插入的內容,fileName爲文件名
    public void insert(String fileName,String model,long pos,String insertContent){
        try {
            //表示以tmp爲後綴的臨時文件,null表示默認
            File tmp = File.createTempFile("tmp",null);
            tmp.deleteOnExit();
            //以讀寫方式來創建文件
            RandomAccessFile raf = new RandomAccessFile(fileName,model);
            //使用臨時文件來保存數據
            FileInputStream tmpIn = new FileInputStream(tmp);
            FileOutputStream tmpOut = new FileOutputStream(tmp);
            raf.seek(pos);
            //----------------------下面代碼將插入點後的內容讀入臨時文件中保存------------------
            int hasRead = 0;
            byte[] bytes = new byte[1024];
            //用循環方式讀取插入點後的數據
            while ((hasRead = raf.read(bytes))>0){
                tmpOut.write(bytes,0,hasRead);
            }
            //-----------------------下面代碼用於插入內容---------------------
            //把文件指針重新定位到POS位置
            raf.seek(pos);
            raf.write(insertContent.getBytes());
            //追加臨時文件中的內容
            while ((hasRead = tmpIn.read(bytes)) > 0) {
                raf.write(bytes, 0, hasRead);
            }
        } catch (IOException e) {
            e.printStackTrace();

          //讀取其他進程的輸出信息
    @Test
    public void readFromProcessTest() {
        try {
            //運行Javac命令,返回該命令的子進程,exec()方法可以運行平臺上的其他程序
            Process p = Runtime.getRuntime().exec("javac");
            //以p進程的錯誤流創建BufferedReader對象,這個錯誤對象是本程序的輸入流,對p進程則是輸出流
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String buff = null;
            //以循環方式來讀取p進程的錯誤輸出
            while ((buff = br.readLine()) != null) {
                System.out.println(buff.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
```

 //使用文件鎖FileLOck鎖定文件
    public static void fileLockTest() {
        //使用FileOutputStream獲取FileChannel
        try (FileChannel fileChannel = new FileOutputStream("a.txt").getChannel()) {
            System.out.println(fileChannel);
            //使用非阻塞方式對指定文件加鎖
            FileLock lock = fileChannel.tryLock();
            //暫停10s
            Thread.sleep(10000);
            //釋放鎖
            lock.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章