【深入JAVA】Java中檔案操作

來源:互聯網
上載者:User

標籤:

在閱讀的過程中有任何問題,歡迎一起交流

郵箱:[email protected]   

QQ:1494713801

 

1、在指定目錄下建立檔案夾及檔案,並寫入初始內容

    File file = new File("filePath");
    File pf = file.getParentFile();
    if(!pf.exists()){
      pf.mkdirs();//建立檔案夾
    }
    if(!file.exists()){
     file.createNewFile();//建立新檔案
    }
    FileWriter fw = new FileWriter(file);
    PrintWriter pw = new PrintWriter(fw);
    pw.append("this is a new file");//寫入初始常值內容
    pw.flush();
    pw.close();

 

2、修改檔案中指定行的內容

     File file = new File("file路徑");
     BufferedReader reader = null;
     try {
             reader = new BufferedReader(new FileReader(file));
             String tempString = "";
             String bufferstr="";
             while ((tempString = reader.readLine()) != null) {
               try {
                  tempString.getBytes("utf-8");
                  if(tempString.startsWith("dburl=")){
                      bufferstr+="替換為新內容"+"\n";
                  }else{
                      bufferstr+=tempString+"\n";
                 }
               } catch (UnsupportedEncodingException e1) {
                 e1.printStackTrace();
               }
          }
          reader.close();
          BufferedWriter writer=new BufferedWriter(new FileWriter(file));
          writer.write(bufferstr);
          writer.close();
      } catch (Exception e) {
         e.printStackTrace();
      }finally {
           if (reader != null) {
               try {
                     reader.close();
               } catch (IOException e1) {
               }
           }
      }

 

3、在目前的目錄下尋找其下及所有子檔案夾中的包含et.txt字元的檔案路徑

    public static File[] searchFile(File folder, final String keyWord) {// 遞迴尋找包含關鍵字的檔案
        
        File[] subFolders = folder.listFiles(new FileFilter() {// 運用內部匿名類獲得檔案
                    public boolean accept(File pathname) {// 實現FileFilter類的accept方法
                        if (pathname.isDirectory() || (pathname.isFile() && pathname.getName().toLowerCase()
                          .equals(keyWord.toLowerCase())))// 目錄或檔案包含關鍵字
                            return true;
                        return false;
                    }
                });
        
        List result = new ArrayList();// 聲明一個集合
        for (int i = 0; i < subFolders.length; i++) {// 迴圈顯示檔案夾或檔案
            if (subFolders[i].isFile()) {// 如果是檔案則將檔案添加到結果清單中
                result.add(subFolders[i]);
            } else {// 如果是檔案夾,則遞迴調用本方法,然後把所有的檔案加到結果清單中
                File[] foldResult = searchFile(subFolders[i], keyWord);
                for (int j = 0; j < foldResult.length; j++) {// 迴圈顯示檔案
                    result.add(foldResult[j]);// 檔案儲存到集合中
                }
            }
        }
        
        File files[] = new File[result.size()];// 聲明檔案數組,長度為集合的長度
        result.toArray(files);// 集合數組化
        return files;
    }

 

參考連結:http://dict.xsoftlab.net/dict/java-find

http://zhidao.baidu.com/link?url=5vnI0uRYDTDcr8SjLULeLpcNhbKtaHCGP5zVQo7KyawswztyL9YxLnXrzxkGTpHWBuyeY4V8fxyGBdMfD57Xgq

【深入JAVA】Java中檔案操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.