I am creating an encryption/decryption program that uses multiple classes. I have one class that is the UI, and uses a JFrame form with a file selector, and another class that encrypts/decrypts the selected file. I am encountering a problem when I try to use the java.io.File variable declared in the UI class in the encryption class.
File selector code:
public static void actionEncrypt() {
encrypt = true;
int retVal = selectFile.showOpenDialog(null);
if (retVal == selectFile.APPROVE_OPTION) {
java.io.File file = selectFile.getSelectedFile();
System.out.println(file);
Crypt.encrypt();
}
}
Variable declaration code:
public static boolean encrypt;
public static java.io.File file;
File reading code:
public static void encrypt() {
System.out.println(MainUI.file);
try {
Scanner filescan = new Scanner(MainUI.file);
int count = 0;
while (filescan.hasNextLine()) {
count++;
filescan.nextLine();
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
When I run this code, I get a NullPointerException because the value of the File variable while the file reading code is running is null. This is because it was declared as static in the variable declaration code, which overwrites the value that was declared in the method actionEncrypt. If I don't make the variable static, I get a Cannot find symbol when I try to access it from the other class. However, I cannot declare the variable as static within the method actionEncrypt, because it gives me an illegal start of expression. Does anyone know how to declare a variable in a method as static without hiding a field, or any other way to use the File variable in another class?
Thanks in advance,
Santiago
"The variable must be static in order to be accessed from other classes."-- this is wrong, so very wrong. Your variable should most definitely not be static. I'm not saying that static variables should never be used, and in fact there are many situations where they are quite helpful, but I am saying that this is not one of those situations. Instead if it must be accessible from other classes, make it an instance variable, and consider giving this class a getter method.staticvariables, or ensure that initialization happens first.Cannot find symbolwhen trying to access it from the encryption class. I edited the question with more precise wording.MainUIwithout instantiating it. In that case, you should have some code in the MainUI that initializes the variablefile, before the encryption code calls it.file? Isn't it already initialized when it is set to the file selected?