2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
嚴(yán)格來(lái)說(shuō)我可能根本不會(huì)使用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貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
對(duì)于第一個(gè),您可以使用以下內(nèi)容:
File f = new File("F:\\program.txt");
if (f.exists())
System.out.println("Exists");
添加回答
舉報(bào)