Java how to create, open, write, and read then close the file -
so here's problem, stack on how create, open, write, , read file, code
import java.util.*; import java.io.*; class class_name{ formatter x; // variable: creating new file file file = new file("file.txt"); // variable: check file existence //creating txt file public void creating_file(){ try{ x = new formatter("file.txt"); }catch(exception e){ system.out.println("you got error"); } } public int check_file(){ if(file.exists()){ return 1; // in main method, check if file exists pass creating file }else{ return 0; // in main method if return value 0, create new file "public void creating_file()" method } } so problem when tried write in file, using class formatter , format text data in before , class formatter won't work if public int check_file() equals 1 because skip creating file using formatter class , can't write in file because variable x undefined
this code how write text in file
public void recording_to_file(){ x.format(format, args); } and closing file need handle error this
public void close_file(){ try{ x.close(); }catch(exception e){ file.close(); } } } there ton of class need 1 file, or maybe there 1 simple class can in 1 like(write, open, read, close), new in java, think maybe in here can help, thank you
take @ this. second argument filewriter costructor (true) tells append data, instead of overwriting any.
import java.util.*; import java.io.*; class someclass{ formatter x; file file = new file("file.txt"); public void creating_file(){ try{ x = new formatter(new filewriter(file, true)); }catch(exception e){ system.out.println("you got error"); } } public boolean check_file(){ return file.exists(); } }
Comments
Post a Comment