亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅當字符串不存在時才將其添加到文件中

僅當字符串不存在時才將其添加到文件中

莫回無 2023-07-28 15:42:46
我正在自學 Java,遇到了一個我不知道如何解決的問題。我基本上想檢查兩件事: 1. 如果文件不存在 - 創建它!如果是這樣,則什么也不做。2. 如果文件包含給定的字符串,則不執行任何操作,如果不包含它 - 添加它?。ú灰采w它)第二個更重要,但我也無法弄清楚第一個。嘗試在線查找如何確保文件存在,或者如何僅在文件不存在時將字符串添加到文件中,但由于某種原因它不起作用。main{        String s;FileWriter fw = new FileWriter("s.txt", true);            File file = new File("s.txt");            doesStringExist(s,fw);   } public void doesStringExist(String s, FileWriter fw) throws IOException {        String scan;        BufferedReader bReader = new BufferedReader(new FileReader(String.valueOf(fw)));        while ((scan = bReader.readLine()) != null) {            if (scan.length() == 0) {                continue;            }            if(scan.contains(s) {                System.out.println(s + " already exists in S.txt");            }else{                fw.write(s);            }        }    }// I made a different method for checking if it exists or not because i just like it like that being more organized目前我希望代碼只檢查字符串是否存在,如果存在,則不執行任何操作(發送存在消息),如果不存在,則將其添加到文件中。我也想這樣做,以便它檢查文件是否存在。
查看完整描述

2 回答

?
慕婉清6462132

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");

  }

}


查看完整回答
反對 回復 2023-07-28
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

對于第一個,您可以使用以下內容:


File f = new File("F:\\program.txt"); 

if (f.exists()) 

    System.out.println("Exists"); 


查看完整回答
反對 回復 2023-07-28
  • 2 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號