What your problem?
If you cannot call tf1.getText() from second class because tf1 is private in first class -> make it public or add public static variable to hold the file name that can refer from second class.
Frage
I'm making a program with Java and I have the problem that I want to write a file in one class. In another class I want to overwrite this file, if the name of the file already exsists. However the first class uses a JTextField in which you can enter a number. That number is than added to the filename. That works perfect, but in the second class it won't. I used an association, but it gave me a nullpointer exception. Can someone help?
public void actionPerformed(ActionEvent e) {
//make file
String fileName = "Week " + tf1.getText();
File planning = new File(fileName + ".txt");
// save file
if (e.getSource() == b2) {
// file does't exists yet and all field are filled out
if (!planning.exists() && allesGevuld()) {
FileWriter fw;
try {
fw = new FileWriter(planning, false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(toString());
bw.close();
fw.close();
JOptionPane.showMessageDialog(null,
"De weekplanning is opgeslagen!", "Succes",
JOptionPane.PLAIN_MESSAGE);
dispose();
} catch (IOException e1) {
System.out.println("Exception ");
}
// no everything is filled in
} else if (!allesGevuld()) {
JOptionPane.showMessageDialog(null,
"Niet alle velden zijn ingevuld!", "Mislukt",
JOptionPane.PLAIN_MESSAGE);
}
// to overwriting frame
else if (planning.exists() && allesGevuld()) {
OverschrijvenFrame ov = new OverschrijvenFrame(planningFrame);
ov.setVisible(true);
}
}
}
Second class:
if (e.getSource() == overschrijf) {
// overschrijven van file
String fileName = "Week"+ ;//this is where the number should be overwritten
File planning = new File(fileName + ".txt");
// delete the file which will be overwritten
planning.delete();
// new file
File nieuw = new File(fileName + ".txt");
FileWriter fw;
try {
fw = new FileWriter(nieuw);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(planningFrame.toString());
bw.close();
fw.close();
dispose();
} catch (IOException e1) {
System.out.println("Exception ");
}
}
}
Lösung
What your problem?
If you cannot call tf1.getText() from second class because tf1 is private in first class -> make it public or add public static variable to hold the file name that can refer from second class.
Andere Tipps
Use Java IO
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists%28%29
import java.io.*;
//...
new File("pathToFile").exists()
OR use Java NIO
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
import java.nio.file.*;
//...
Files.exists(Paths.get("pathToFile"))