2 回答

TA貢獻1804條經驗 獲得超2個贊
嚴格來說我可能根本不會使用exists(),只需使用異常路徑:
File file = new File("s.txt"); // this is a file handle, s.txt may or may not exist
boolean found=false; // flag for target txt being present
try(BufferedReader br=new BufferedReader(new FileReader(file))){
String line;
while((line=br.readLine())!=null) // classic way of reading a file line-by-line
if(line.equals("something")){
found=true;
break; // if the text is present, we do not have to read the rest after all
}
} catch(FileNotFoundException fnfe){}
if(!found){ // if the text is not found, it has to be written
try(PrintWriter pw=new PrintWriter(new FileWriter(file,true))){ // it works with
// non-existing files too
bw.println("something");
}
}

TA貢獻1815條經驗 獲得超6個贊
對于第一個,您可以使用以下內容:
File f = new File("F:\\program.txt");
if (f.exists())
System.out.println("Exists");
添加回答
舉報