[英]Add a string to a file ONLY if it doesn't exist
I'm teaching myself Java and came across a problem which I have no idea how to solve. 我在自学Java,遇到一个我不知道如何解决的问题。 I want to basically check two things: 1. If a file doesn't exist - create it! 我想基本上检查两件事:1.如果文件不存在-创建它! if it does, do nothing. 如果可以,则什么也不做。 2. If the file contains a given String, do nothing, if it does not contain it - add it! 2.如果文件包含给定的字符串,则不执行任何操作(如果不包含该字符串)-添加它! (don't overwrite it) 2nd one is more important but I couldn't figure out the first one either. (不要覆盖它)第二个更重要,但我也无法弄清楚第一个。
Tried looking online on how to make sure a file exists, or how to only add String to a file if it doesn't exist, but it just doesn't work for some reason. 尝试在线查看如何确保文件存在,或者如何仅将String添加到文件(如果文件不存在),但是由于某种原因它不起作用。
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
Currently I expect the code to only check if a string exists, if it does, do nothing (send exists message), if it doesn't exist, add it to the file. 目前,我希望代码仅检查字符串是否存在,如果不存在,则不执行任何操作(发送存在的消息),如果不存在,则将其添加到文件中。 also I want to make it so it checks if the file exists. 我也想制作它,以便它检查文件是否存在。
For 1st one you can use the below : 对于第一个,您可以使用以下代码:
File f = new File("F:\\program.txt");
if (f.exists())
System.out.println("Exists");
Strictly said I might not use exists()
after all, just go with the exception-path: 严格地说,我可能根本不使用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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.