nullpointerexception error on cancel or closing dialog - java

My problem is when my showopendialog appears and I press cancel or the X on the right corner instead of loading some text in my textarea, the console shows the error of nullpointexception on my line String filename=f.getAbsolutePath();
My action open is on a menu bar.
Thank you.
JFileChooser flcFile = new JFileChooser("c:\\");
flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
String filename=f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}

If you close without selecting a file, you can't get the absolute path of the file. Always check if a file has been selected by the user by checking the value returned by the showOpenDialog() method. Only get the absolute path after this check.
Useful reading: The JFileChooser docs.
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File f = flcFile.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}

Hello I modified your code, check the following example:
public class Main {
public static void main(String[] args) {
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
if (JFileChooser.CANCEL_OPTION == result) {
System.out.println("canceled");
} else if (JFileChooser.APPROVE_OPTION== result) {
String filename = f.getAbsolutePath();
System.out.println(filename);
}else{
System.out.println(result);
}
}
}
You need to check the return value of the showOpenDialog method in order to know the selected option, I hope it help you
cheers.

Related

How to use JFileChooser to show in a table a csv file with any name to read and edit this same file

I made a program to help me with some spreadsheets and it works perfectly, but I would like to be able to select any csv file using JFileChooser and to be able to edit the file that was selected. The way I did it, I always force the file to have a specific name and i dont want like this.
How can I do this? I've done some research, but to no success. Thanks
enter code here
//my list, write, remove and update file
File fileName = new File("file.csv");
#Override
public ArrayList<Data> list() throws Exception {
try{
ArrayList<Data> listData = new ArrayList<>();
FileReader fr = new FileReader(fileName);
try (
BufferedReader br = new BufferedReader(fr)) {
String line;
while((line=br.readLine())!=null){
Data objData = new Data(line);
listData.add(objData);
}br.close();
}
return listData;
}catch(IOException erro){
throw erro;
}
}
#Override
public void add(Data objData) throws Exception {
try{
FileWriter fw = new FileWriter(fileName,true);
try (
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(objData.toString()+"\n");
}
}catch(IOException erro){
throw erro;
}
}
#Override
public void remove(int code) throws Exception{
ArrayList<Data> list;
list = list();
if(list.isEmpty()) return;
FileWriter fw = new FileWriter(fileName);
try (
BufferedWriter bw = new BufferedWriter(fw)) {
for(Data p : list){
if(p.getCode() != code){
bw.write(p.toString()+"\n");
}
}
}
}
#Override
public void update(Data objData) throws Exception {
try{
ArrayList<Data> list;
list = list();
if(list.isEmpty()) return;
FileWriter fw = new FileWriter(fileName);
try (
BufferedWriter bw = new BufferedWriter(fw)) {
for(Data p : list){
if(p.getCode() != objData.getCode()){
bw.write(p.toString()+"\n");
}else{
bw.write(objData.toString()+"\n");
}
}
}
}catch(Exception erro){
throw erro;
}
}
enter code here
//my UI table list
private void showData(){
try{
ArrayList<Data> list;
DataDAO Data = new DataDAO();
list = Data.list();
if (list.isEmpty()) return;
DefaultTableModel model = (DefaultTableModel) jTable_Table1.getModel();
model.setNumRows(0);
for(int pos=0; pos < list.size(); pos++){
String[] line = new String[6];
Data aux = list.get(pos);
line[0] = aux.getCode()+"";
line[1] = aux.getName();
line[2] = aux.getPrice()+"";
line[3] = aux.getCargoN()+"";
line[4] = aux.getTotal_Weight()+"";
line[5] = aux.getTotal_Vol()+"";
model.addRow(line);
}
}catch (Exception erro){
JOptionPane.showMessageDialog(rootPane, erro.getMessage());
}
}
// MY button jfilechooser
private void open_file() throws Exception{
try{
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Only csv", "csv");
chooser.setFileFilter(filter);
chooser.setCurrentDirectory(new File("./"));
int result = chooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
String file = selectedFile.getAbsolutePath();
System.out.println(file);
showData();
}
}catch(HeadlessException erro){
JOptionPane.showMessageDialog(rootPane, erro);
}
}
In simple terms, something like ...
private JFileChooser fileChooser;
public File getFile(Component parent) {
if (fileChooser == null) {
fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Make a choice");
FileNameExtensionFilter filter = new FileNameExtensionFilter("csv", "CSV");
fileChooser.addChoosableFileFilter(filter);
}
int option = fileChooser.showOpenDialog(parent);
if (option == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile();
}
return null;
}
Which is largely covered by How to Use File Choosers
You could add this to your existing class or make a utility class depending on your needs.
You will need to change your workflow to have some kind of "open file" step, which would call this and return the "selected file", making sure you take into account the possibility of a null value. You'd then assign this value to File fileName;, this would allow your other workflows to continue operating.
The "hows" of how you would do this are implementation dependent and you're going to have to play around with yours to figure out the best place(s) to make use of it

Scanner, Select File on Computer

Now, I read my .txt file by telling where is this file.
I want to change to I can select a file on my computer. How can I do that?
Scanner file = new Scanner(new File("Sample.txt"));
while (file.hasNextLine()) {
String input = file.nextLine();
}
Here is a runnable you can try. Like #Verity has stipulated, use the JFileChooser. Read the comments within the following code:
public class JFileChooserWithConsoleUse {
public static void main(String[] args) {
// A JFrame used here as a backbone for dialogs
javax.swing.JFrame iFrame = new javax.swing.JFrame();
iFrame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
iFrame.setAlwaysOnTop(true);
iFrame.setLocationRelativeTo(null);
String selectedFile = null;
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new java.io.File("C:\\"));
fc.setDialogTitle("Locate And Select A File To Read...");
int userSelection = fc.showOpenDialog(iFrame);
// The following code will not run until the
// FileChooser dialog window is closed.
iFrame.dispose(); // Dispose of the JFrame.
if (userSelection == 0) {
selectedFile = fc.getSelectedFile().getPath();
}
// If no file was selected (dialog just closed) then
// get out of this method (which in this demo ultimately
// ends (closes) the application.
if (selectedFile == null) {
javax.swing.JOptionPane.showMessageDialog(iFrame, "No File Was Selected To Process!",
"No File Selected!", javax.swing.JOptionPane.WARNING_MESSAGE);
iFrame.dispose(); // Dispose of the JFrame.
return;
}
// Read the selected file... 'Try With Resources' is
// used here so as to auto-close the reader.
try (java.util.Scanner file = new java.util.Scanner(new java.io.File(selectedFile))) {
while (file.hasNextLine()) {
String input = file.nextLine();
// Display each read line in the Console Window.
System.out.println(input);
}
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
}
}
In this case you need to use an JFileChooser

Comparing ArrayList with user input

I have been trying to compare the file content with user input. The program is reading from a specific file and it checks against the user's string input. I am having trouble comparing the ArrayList with the user input.
public class btnLoginListener implements Listener
{
#Override
public void handleEvent(Event arg0)
{
//variables for the class
username = txtUsername.getText();
password = txtPassword.getText();
MessageBox messageBox = new MessageBox(shell, SWT.OK);
try {
writeFile();
messageBox.setMessage("Success Writing the File!");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when writing the file!");
}
try {
readFile("in.txt");
} catch (IOException x)
{
messageBox.setMessage("Something bad happened when reading the file!" + x);
}
if (username.equals(names))
{
messageBox.setMessage("Correct");
}
else
{
messageBox.setMessage("Wrong");
}
messageBox.open();
}
}
private static void readFile(String fileName) throws IOException
{
//use . to get current directory
File dir = new File(".");
File fin = new File(dir.getCanonicalPath() + File.separator + fileName);
// Construct BufferedReader from FileReader
BufferedReader br = new BufferedReader(new FileReader(fin));
String line = null;
while ((line = br.readLine()) != null)
{
Collections.addAll(names, line);
}
br.close();
}
I am assuming you are trying to check whether an element exists in the list. If yes, then you need to use contains method, here's the Javadoc.
So, instead of using if (username.equals(names)), you can use if (names.contains(username)).
Apart from this, you should make the following changes:
Don't read the file every time an event is called. As you are reading a static file, you can read it once and store it in an ArrayList.
Make variables username and password local.
Remove writeFile() call unless it's appending/writing dynamic values on each event.

How to set the save path for a file chosen in filechooser JavaFX

I searched around but couldn't find nothing on this.
I would like to set the save (destination) path for a file selected in Filechooser. For example, I selected a picture called 'test.jpg', I would like for this 'test.jpg' to be saved to C:\blah\blah\blah\Pictures. How can I pull this off?
So far the code I have
public void OnImageAddBeer(ActionEvent event){
FileChooser fc = new FileChooser();
//Set extension filter
fc.getExtensionFilters().addAll(new ExtensionFilter("JPEG Files (*.jpg)", "*.jpg"));
File selectedFile = fc.showOpenDialog(null);
if( selectedFile != null){
}
}
All you need to do is copy the content inside the file choose in wherever you want, try something like this:
if(selectedFile != null){
copy(selectedFile.getAbsolutePath(), "C:\\blah\\blah\\blah\\Pictures\\test.jpg");
}
and the method copy:
public void copy(String from, String to) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(from);
fw = new FileWriter(to);
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
//...
}
}
Basically copy just copy the content of the file located in from inside a new file located at to.
Try this:
String fileName = selectedFile.getName();
Path target = Paths.get("c:/user/test", fileName);
Files.copy(selectedFile.toPath(), target);
Add this statement if you want to set the destination path:
fc.setInitialDirectory(new File(System.getProperty("user.home") + "\\Pictures"));
Take this:
String dir = System.getProperty("user.dir");
File f = new File(dir + "/abc/def");
fc.setInitialDirectory(f);

Insert selected file to FileReader

i want to take selected file in another class and insert it to other class in method doit() for variable in in FileReader().
how can i insert in method doit(), in class Element,not this file "D:\Probe.txt",
public void doit() {
try {
in = new BufferedReader(new FileReader("D:\\Probe.txt"));
out = new StreamResult("D:\\data.xml");
initXML();
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
closeXML();
} catch (Exception e) {
e.printStackTrace();
}
}
Notably this file, that in patch variable from class Dialog,
`
if (cmd.equals("Quelldatei auswählen")) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int ret = fileChooser.showDialog(this, "auswählen");
if (ret == JFileChooser.APPROVE_OPTION) {
File patch = fileChooser.getSelectedFile();
contentPane.add(new JLabel("Quelldatei ist: " + patch));
}
I understood your problem like you want the file in your doit() method without using the BufferedReader inside this method?
if im right, try this:
Save your file in a File Object and give this object as a parameter to your doit() method like:
public void doit(File file){
...
}

Categories

Resources