Some Basic file handling questions
hey i've just moved onto file handling but the way ive learnt to handle files seems a bit untidy and i was wondering if there is a better way to handle files compared to how i am doing it. below is my code
What i dont like about this code is that im creating 3 objects all of different classes to basically handle one file. is there not one object which can do it all?
ie check the file exists, read from it, write to it, delete it etc?
Code:
public class GUI extends JFrame{
private Scanner fileReader; // used for reading files
private File fileHandle; //used for checking file exists
private Formatter fileCreator; //used for creating files
public boolean checkFile(String fileNamePassed){
boolean exists = false;
try{
fileHandle = new File(fileNamePassed);
if(fileHandle.exists())
exists = true; //return true if File name exists
}catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage());}
return exists;
}
public void createFile(String fileNamePassed){
try{
if (checkFile(fileNamePassed) == false ) //If no File exists
fileCreator = new Formatter(fileNamePassed); //Blank File created
else
JOptionPane.showMessageDialog(null, "file already exists");
}catch(Exception e){
JOptionPane.showMessageDialog(null,e.getMessage());}
}
public void readFile(String fileNamePassed){
try{
if (checkFile(fileNamePassed) == true) //If File exists
fileReader= new Scanner(new File(fileNamePassed)); //initiate reader object
//some reading code here
else
JOptionPane.showMessageDialog(null, "file doesn't exists");
}catch(Exception e){}
}
}