[英]File is being recreated even though it already exists
How does this code delete the file I had and makes a new one?? 此代码如何删除我拥有的文件并制作一个新文件?
public void actualizaJTextArea(String cliente){
mensagens.setText("");
Scanner scanner = null;
File file = createFile(cliente + "chatswith.txt");
try {
scanner = new Scanner(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(...)
scanner.close();
}
public static File createFile(String s){
File file = new File(s);
if(!file.exists()){
try {
boolean b = file.createNewFile();
System.out.println(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
Does the method createNewFile()
do this? 方法createNewFile()
是否这样做? Thanks and I'm sorry if this has been asked before I just can't find it. 谢谢,对于在我找不到之前问过这个问题,我们感到抱歉。
EDIT 编辑
I am also using createFile()
in here to write in it but the use is the same so i guess that can't be it: 我也在这里使用createFile()
来编写它,但是用法是一样的,所以我想不可能是这样:
public void recebeMensagem(boolean b){
while(true){
Mensagem m = null;
try {
m = (Mensagem)input.readObject();
System.out.println("Mensagem Recebida:"+m);
} catch (ClassNotFoundException e){
} catch (IOException e) {
try {
input.close();
System.out.println("Server desligou...");
break;
} catch (IOException e1) {
}
}
if(m != null){
for(Mensagens mensagens:v){
for(String string: m.getReceivers()){
if (mensagens.getCliente().equals(m.getAuthor()) && mensagens.getContacto().equals(string)){
mensagens.actualizaJTextArea(cliente);
}
}
}
for(String Str :m.getReceivers()){
PrintWriter p = null;
File file = Mensagens.createFile(cliente + "chatswith.txt");
try {
p = new PrintWriter(new FileWriter(file));
p.append(m.getAuthor()+"</<"+Str+"</<"+m.getText()+"\n");
p.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
createNewFile() is atomic and it will not delete the file if it is present. createNewFile()是原子的,它不会删除该文件(如果存在)。 Please look at the boolean output, it should be false if your file exists already. 请查看布尔输出,如果您的文件已经存在,则应为false。
EDIT 编辑
add append parameter to FileWriter. 将附加参数添加到FileWriter。 It is overwriting every time. 每次都覆盖。
FROM 从
p = new PrintWriter(new FileWriter(file)); p =新的PrintWriter(新的FileWriter(文件));
TO 至
p = new PrintWriter(new FileWriter(file,true)); p = new PrintWriter(new FileWriter(file,true));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.