How to allow file creation with JFileChooser - java

I am using a JFileChooser to allow the user to select a file and save the current game to it. The problem is that it allows just file selection, and it does not let create a file on the fly and save the game on it. Without creating a custom class, is there a way to allow this behavior in JFileChooser? I am using the file chooser to just select files, this is the code that I've written:
JFileChooser chooser= new JFileChooser();
chooser.setMultiSelectionEnabled(false);
chooser.setDialogTitle("Save the current game");
chooser.setFileFilter(new FileNameExtensionFilter("Poker","Poker"));
int value= chooser.showSaveDialog(this);
if(value== JFileChooser.APPROVE_OPTION)
{
File file= chooser.getSelectedFile();
System.out.println("Selected file " + file);
BufferedWriter writer= null;
try
{
writer= new BufferedWriter(new FileWriter(file));
writer.write(APP_ID);
writer.write(tax);
writer.write(money);
}
catch(Exception e)
{
System.out.println("Failed to write file: " + e);
}
finally
{
if(writer!= null)
{
try
{
writer.close();
}
catch(Exception e)
{
System.out.println("Failed to close file: " + e);
}
}
}
}

Related

How to call a method that creates a JFileChooser dialog from a different class

I have been trying to call a method in another class that instantiates a new JFileChooser dialog. Everything seems to work ok except that the APPROVE_OPTION code
int userSelection = chooser.showSaveDialog(chooser);
if (userSelection == JFileChooser.APPROVE_OPTION) {
System.out.println("File saved " + chooser.getSelectedFile().getName());
}
doesn't appear to work.
Below is the method contains the createFile method that has the JFileChooser within
public class TextFileHandler {
private static final String COMMA_DELIMITER = ",";
private static final String NEW_LINE_SEPARATOR = "\n";
private static JFileChooser chooser;
private static int userSelection;
public void createFile(String shiftPattern) {
chooser = new JFileChooser();
chooser.setSelectedFile(new File(shiftPattern + "_export"));
chooser.setDialogTitle("Save shift pattern to CSV format");
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV", "csv");
chooser.setFileFilter(filter);
int userSelection = chooser.showSaveDialog(chooser);
if (userSelection == JFileChooser.APPROVE_OPTION) {
System.out.println("File saved " + chooser.getSelectedFile().getName());
}
}
The below file is an excerpt of the class that calls the above method from a button press action.
else if (action.equals("EXPORT_CSV_BUTTON")) {
TextFileHandler textFile = new TextFileHandler();
String temp = copyPatternController.getShiftPatCode();
messageShow(new Integer(TextFileHandler.getUserSelection()).toString() + " and "
+ (TextFileHandler.getChooser().APPROVE_OPTION)); //for debugging
textFile.createFile(temp);
FileWriter fw = null;
try {
File file = new File(temp + "_export.csv");
fw = new FileWriter(file);
fw.append("testing");
} catch (IOException e) {
System.out.println("Error in writing csv file !!!");
e.printStackTrace();
} finally {
try {
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The save dialog appears ok but when i press save the dialog closes and nothing is created. Appreciate any ideas
In the EXPOPRT_CSV_BUTTON I was missing a getSelectedFile() call.
File file = new File(TextFileHandler.getChooser().getSelectedFile().getPath() + ".csv");
The creates the file with no problems. I have also refactored my obfuscated code thank you for pointing that out.

Trying to send data to text file

Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..

How to save file.txt with JFileChooser?

I am developing notepad project, would like know how do for save a file.txt, my problem is, I keep the file opening JFileChooser, after selected the local where save intend, but after if save again will open JFileChoose again. I want save. Not save as.
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
PrintStream fileOut = null;
try {
File file = fc.getSelectedFile();
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (FileNotFoundException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
fileOut.close();
}
Change you work flow.
Basically, when you first save the file, you need to keep a reference to the File to which you saved to...
public class ... {
private File currentFile;
Now, when you go to save the file, you need to check if the currentFile is null or not. It it is null, you ask the user to select a file, otherwise, you can go ahead and try and save the file...
if (currentFile == null) {
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
}
}
// Used to make sure that the user didn't cancel the JFileChooser
if (currentFile != null) {
PrintStream fileOut = null;
try {
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (IOException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileOut.close();
} catch (IOException exp) {
}
}
If you want a save as an alternate to a save as, have the program store a File object referencing the currently opened file's path so the program is always aware of what it's editing, then just write to the programs file variable

How to Create or edit a txt file in a folder in Java?

I'm trying to make save files for a game i'm making, these files will have multiple txt files in them. My problem is that both the folder and the txt file wont create themselves in the directory I specify, here is the code for the folder:
File folde = new File("c:/Users/Mike/Desktop/Saves/bob/" + save);
try{
if (!folde.exists()) {
if (folde.mkdirs()) {
System.out.println("Created new save file");
} else {
System.out.println("Did not create new save file");
}
}
}finally{
System.out.println("Folder found.");
}
Here is the code for the file:
try{
PrintWriter writer = new PrintWriter("c:/Users/Mike/Desktop/javafiles/Saves/" + save + "/Stats.txt", "UTF-8");
writer.println(Stats.Health);
writer.println(Stats.Strength);
writer.println(Stats.Constitution);
writer.println(Stats.Dexterity);
writer.println(Stats.Inteligence);
writer.println(Stats.Wisdom);
writer.println(Stats.Charisma);
writer.close();
} catch (IOException x) {
System.err.println("Could not create save file.");
}
And here is the entire Class:
package files.maintain;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import vars.all.*;
public class SaveFile {
MainStart Start = new MainStart();
Stats Stats = new Stats();
public void save(){
Scanner in = new Scanner(System.in);
System.out.println("What should I save as?");
String save = in.nextLine();
File folde = new File("c:/Users/Dave/Desktop/Saves/bob/" + save);
try{
if (!folde.exists()) {
if (folde.mkdirs()) {
System.out.println("Created new save file");
} else {
System.out.println("Did not create new save file");
}
}
}finally{
System.out.println("Folder found.");
}
try{
PrintWriter writer = new PrintWriter("c:/Users/Dave/Desktop/javafiles/Saves/" + save + "/Stats.txt", "UTF-8");
writer.println(Stats.Health);
writer.println(Stats.Strength);
writer.println(Stats.Constitution);
writer.println(Stats.Dexterity);
writer.println(Stats.Inteligence);
writer.println(Stats.Wisdom);
writer.println(Stats.Charisma);
writer.close();
} catch (IOException x) {
System.err.println("Could not create save file.");
}
}
}
The Response i'm getting from the console is:
What should I save as?
bob
Folder found.
Could not create save file.*
My input is in bold,
I checked this website: http://www.mkyong.com/java/how-to-create-directory-in-java/
And the java tutorials: http://docs.oracle.com/javase/tutorial/essential/io/file.html
But that didn't work.
Thanks!
Make paths consistent if not the same. Instead of using string constants, use a single Java File object. You are using these 2 inconsistent prefixes:
"c:/Users/Dave/Desktop/Saves/bob/"
"c:/Users/Dave/Desktop/javafiles/Saves/"
Also, you need to improve your exception handling and reporting. Log as much information as you can about the original exception and the corrective (or emergency) action your program is taking.

Create a File if it is not already there

In Java we can create a reference to a file by...
File counterFile = new File("countervalue.txt");
but how do we create the file if it does not already exist?
The basic way to create the file would be calling the File#createNewFile method:
File counterFile = new File("countervalue.txt");
try {
counterFile.createNewFile();
} catch (Exception e) {
System.out.println("File couldn't been created.");
}
Now, if you want to create a new File and fill it with data, you can use a FileWriter and a PrintWriter for text files (assuming this for the txt extension in your sample):
File counterFile = new File("countervalue.txt");
PrintWriter pw = null;
try {
//it will automatically create the file
pw = new PrintWriter(new FileWriter(counterFile));
pw.println("Hello world!");
} catch (Exception e) {
System.out.println("File couldn't been created.");
} finally {
if (pw != null) {
pw.flush();
pw.close();
}
}
If you want to just append data to your file, use the FileWriter(File, boolean) constructor passing true as the second parameter:
pw = new PrintWriter(new FileWriter(counterFile, true));
Easily done in java
File counterFile = new File("countervalue.txt");
counterFile.createNewFile();

Categories