There is no existence of the saved file.How to do that? - java

while i am trying to save the file its not working but for making folders it works. what should i do ? i am new in java also. plz help
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==save)
{
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
}
}

You choose a file but don't create it write anything to it. The file will not be created until you actually create it or write something to it, for example with
FileWriter writer = new FileWriter(fileToSave);
writer.write("Hello!");
writer.close();

First, get the file you want to save as a File.
Then, write it to a new directory using BufferedWriter to a new directory.
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(aComponent); //parent component to JFileChooser
if (returnVal == JFileChooser.APPROVE_OPTION) { //OK button pressed by user
File file = fc.getSelectedFile(); //get File selected by user
o = new BufferedWriter(new FileWriter(file)); //use its name
//write things here
o.flush();
o.close();
}
Look at How to save file using JFileChooser in Java? and How to save a txt file using JFileChooser?

Related

How to prompt user for file name?

export content to an xls file using java with save dialog:
- Where should I ask for a file name during save?
I prefer to ask what to name the file when it is saved.
public static void main(String args[])
{
SaveToExcel exp = new SaveToExcel();
exp.writePropertiesIntoExcel("D:\\ExcelFile.xls");
}
You should use JFileChooser if you want to let the users choose where to save the file.
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.APPROVE_OPTION);
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION){
File f = chooser.getSelectedFile();
String a = f.getAbsolutePath();
SaveToExcel exp = new SaveToExcel();
exp.writePropertiesIntoExcel(a);
}
A simple code you can use in your method, this gets the path you want to save your file in.

File not saved using JFileChooser in Java

Iam a java beginner.
I have written a simple program to write some contents to a file using showSaveDialoge() in JFileChooser. The code including below.
public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
try {
File file = new File("fileName.txt");
fc.setSelectedFile(file);
int r = fc.showSaveDialog(frame);
if(r == JFileChooser.APPROVE_OPTION)
{
FileWriter writer = new FileWriter(file);
writer.append("Data inside the file");
writer.flush();
writer.close();
}
else if(r == JFileChooser.CANCEL_OPTION) {
System.out.println("Do nothing for CANCEL");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}
the code gets executed and Save Dialogue box has come. But when I click SAVE button on Dialogue box, nothing had happening. The file has not saved in the selected location. What may be the reason.?
Thanks in advance.
What is hapenning is:
you create a File in your current location with name fileName.txt
File file = new File("fileName.txt"); //could be $HOME$/fileName.txt
User selects ProgramFiles/file.txt
but you uses on FileWritter file information, not what user chossed from FileChooser.
change
FileWriter writer = new FileWriter(file);
to
FileWriter writer = new FileWriter(chooser.getSelectedFile());
Try this:
FileWriter writer = new FileWriter(fc.getSelectedFile());
It should write to selected file from file chooser.
You were writing to fileName.txt which will be saved in current directory from which you run program.

How to use JFileChooser to find a file location

Is there a method that i can use to simply find a file location? I'm trying allow the user to choose a file and open it, but I have to have the JFileChooser just choose the file and send the location to another method. What's the best way to do this?
The example in the javadoc show show to do this:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
That's what chooser.getSelectedFile() is doing. Take the result of that and pass it to another method.
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// You can use
// chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); too
File file = chooser.getSelectedFile();
String fullPath = file.getAbsolutePath();
Then Pass the String to the other method.
We can also use TextArea to get paths of any file example here for Image File and the name of
object TextArea is txtPath, and we make ActionPerformed to JButton named bChoose with the folowing method.
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image Files", "jpg", "png", "gif");
fc.setFileFilter(filter);
fc.showDialog(bChoose, "Choose File");
String strPath = txtPath.getText() + "\n" + fc.getSelectedFile().toString();
txtPath.setText(strPath);

How to save the text file in a path given by JFileChooser?

I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.

JFileChooser to open multiple txt files

How can I use JFileChooser to open two text files and after I selected these files, I want to compare them, show on the screen etc. Is this possible?
You can have your JFileChooser select multiple files and return an array of File objects instead of one
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(frame);
File[] files = chooser.getSelectedFiles();
The method showOpenDialog(frame) only returns once you click the ok button
EDIT
So do this:
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(frame);
File[] files = chooser.getSelectedFiles();
if(files.length >= 2) {
compare(readFileAsList(files[0]), readFileAsList(files[1]));
}
And change your readFileAsList to:
private static List<String> readFileAsList(File file) throws IOException {
final List<String> ret = new ArrayList<String>();
final BufferedReader br = new BufferedReader(new FileReader(file));
try {
String strLine;
while ((strLine = br.readLine()) != null) {
ret.add(strLine);
}
return ret;
} finally {
br.close();
}
}
You can use:
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
// Show the dialog; wait until dialog is closed
chooser.showOpenDialog(frame);
// Retrieve the selected files.
File[] files = chooser.getSelectedFiles();
You can then use the file handles returned to do the compare.
In my case I solved it declaring frame as an initialized local variable set to null:
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
Component frame = null;
chooser.showOpenDialog(frame);
File[] files = chooser.getSelectedFiles();

Categories