How can i save .txt file at desired location using JFileChooser - java

Using following code i can store program.txt in a working project folder, but how can I use JFileChooser or any other option to save file at a selected location?
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
o = new BufferedWriter(new FileWriter("program.txt"));
o.write(t1.getText());
o.write(",");
o.write(t2.getText());
o.write(",");
o.write(t3.getText());
o.write(",");
o.write(t4.getText());
o.write(",");
o.write(t5.getText());
o.write(",");
o.write(t6.getText());
o.write(",");
o.write(t7.getText());
o.write(",");
o.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
});

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
...
//your writing code goes here
}

You can do this way by setting File object in JFileChooser object
File f = new File("filename");
myJFileChooser.setSelectedFile(f);
check this post for more
http://www.coderanch.com/t/561950/GUI/java/Save-JTextArea-JFileChooser-TXT-file

Related

How To Open File Dialog And Create File On It?

1
I opened File Dialog but I don't create the file on it? How?
JFileChooser fileChooser = new JFileChooser();
File selectedFile = null;
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (**result == JFileChooser.APPROVE_OPTION**) {
selectedFile = fileChooser.getSelectedFile();
} else {
confirmExit();
return;
}
To save a file with JFileChooser, you need to use the showSaveDialog() method instead of the showOpenDialog() like in your snippet. For more information check out How to use File Choosers and check out the JFileChooser JavaDoc.
Then the next step if the saving has been approved, is to actually write the file.
For this, you can use a FileWriter.
I put together a small snippet, which opens a JFileChooser on a button click, where you can provide the filename, where some String will be written to this file.
Example:
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> buildGui());
}
private static void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Save your File");
// action listener for the button
btn.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser(); // create filechooser
int retVal = fileChooser.showSaveDialog(frame); // open the save dialog
if (retVal == JFileChooser.APPROVE_OPTION) { // check for approval
// create a bufferedwriter with the specified file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
// write the content to the file
writer.write("Your content that shall be written to the file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Output:

Opening a file without the extension - Java

Im doing a project for my college, my save/opening file are working all right, but I need them to save as my desired extension, and open like that as well.
For example: When I click on Save File, I write the name testFile as file name and hit save, now the my code must save as my desired extension. Same works for opening file, if I write testFile and hit open, it must locate the testFile.txt. Anyone can give me a hand how I should do this? follow my code below.
private class SalvaDesenho implements ActionListener {
private Component parent;
SalvaDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Arquivo de Texto (.txt)", "txt"));
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showSaveDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
return;
int op = 0;
if (fc.getSelectedFile().exists()) {
Object[] options = { "Sim", "Não" };
op = JOptionPane.showOptionDialog(null, "O arquivo já existe deseja substituilo?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
}
if (op != 0) return;
System.out.println("Salvando: " + fc.getSelectedFile().getPath());
FileOutputStream fout = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(figuras);
isSaved = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class AbreDesenho implements ActionListener {
private Component parent;
AbreDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter("Arquivo de texto (.txt)", "txt");
fc.setFileFilter(txtFilter);
int returnVal = fc.showOpenDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
System.out.println("File error!");
System.out.println("Abrindo: " + fc.getSelectedFile().getPath());
FileInputStream fin = new FileInputStream(fc.getSelectedFile());
ObjectInputStream ois = new ObjectInputStream(fin);
figuras = (Vector<Figura>) ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
pnlDesenho.getGraphics().clearRect(0 , 0, parent.getHeight(), parent.getWidth());
for (int i=0 ; i<figuras.size(); i++)
figuras.get(i).torneSeVisivel(pnlDesenho.getGraphics());
}
}
Thanks.
You have to do this manually:
Get the File object from the JFileChooser
Get its absolute path as a String, using getAbsolutePath().
Check whether it has an extension or not: Check file extension in Java
If not, add your extension to the path: path = path+".txt";
Create a new File object from the path: File file = new File(path)
Open/Save the file (your code)

How to add a new line when I print a text from a textarea to a file?

When I print a text that is in a JTextArea in a file it prints it in the same line . How can I add a new line in the file each time I have a new line in the JTextArea ?
This is my code .
print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null)== JFileChooser.APPROVE_OPTION){
File file = fileChooser.getSelectedFile();
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(valid.getText() );
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
Simply use this function from your BufferedWriter object:
bw.newLine();
This command isn't the same like: <br> or \n

JFileChooser component display weird

I'm trying to open a file in filechooser dialog, however, when i opened a file or simply close the dialog. The dialog appears again, i have to close it twice. Here is my code, don't know what's wrong with it
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
ObjectInputStream input;
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
this code lines to create first one
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
openFileChooser.showOpenDialog(null);
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
input.close();
}
and rest of code lines to embeding second one
javax.swing.JFrame openFileFrame = new javax.swing.JFrame();
openFileFrame.setLayout(new BorderLayout());
openFileFrame.setLocationRelativeTo(null);
openFileFrame.add(openFileChooser, BorderLayout.CENTER);
openFileFrame.pack();
openFileFrame.setVisible(true);
Remove the first occurrence of openFileChooser.showOpenDialog(null);

Unable to figure how to store "Save As" text in a string and use it

I am new to UI design in Java. I am trying to create a GUI to download a file off the Internet and save it on your hard drive. I have got the code working except for one thing which I want to add. I have added a JFileChooser which lets the user select the destination folder. But I am unable to figure out how to change the filename to the one which user enters in the Save As bar on the JFileChooser menu.
Browse Button
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}
});
Download Button
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(DESTINATION_FOLDER + "/" + filename);
Here filename should be the one which user enters. Pointers on how to get this done?
Actually you don't need to get the FileName from the Save As Bar in the JFileChooser.
Just do like this:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
//Don't use the 'FileSelectionMode();'. Let it be Default.
chooser.setAcceptAllFileFilterUsed(true);
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
file = chooser.getSelectedFile();
//file should be declared as a File.
System.out.println("The location to save is: " + chooser.getCurrentDirectory();));
System.out.println("The FileName is: " + file.getName());
}
}
DOWNLOAD BUTTON:
URLConnection connection = downloadUrl.openConnection();
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(file);
Without seeing more of your code the best I could suggest is to create a Global String in the class you are working in.
public class gui extends JFrame{
public String filePath="";
public static void main(String args[]){
//button code
browseButton.addActionListener(new ActionListener())
saveAsButton.addActionListener(new ActionListener())
URLConnection connection = downloadUrl.openConnection();
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("browseButton"){
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: "+chooser.getCurrentDirectory());
filePath = chooser.getCurrentDirectory().toString();
}
else{
//save as button selected
input = new BufferedInputStream(connection.getInputStream());
output = new FileOutputStream(filePath);
}
}
}
Add this line:
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
Full code:
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(null);
chooser.setDialogTitle("Select folder to save");
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
//chooser.showDialog(downloadButton, "Save");
if(chooser.showSaveDialog(downloadButton) == JFileChooser.APPROVE_OPTION)
{
System.out.println("The location to save is: " + chooser.getCurrentDirectory());
DESTINATION_FOLDER = chooser.getCurrentDirectory().toString();
}
}

Categories