標籤:
在閱讀的過程中有任何問題,歡迎一起交流
郵箱:[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中檔案操作