I am trying to change a program I wrote a while ago. Currently the program handles a few BufferedReader and BufferedWriters with some logic built in. Let me explain how it used to work.
Class used to upload a file:
public void getFile(){//Used to upload the ACH file.
while(uploadApproval==false){//While upload approval has not been given..
JFileChooser chooser = new JFileChooser();//Creates a new object of the JFileChooser class.
uploadFile = chooser;//Saves the upload file variable as the chooser response.
FileNameExtensionFilter filter = new FileNameExtensionFilter("ACH Files", "ach");
//Sets the allowed file formats for upload.
chooser.setFileFilter(filter);//Activates the created file filter.
chooser.setDialogTitle("Please choose ACH file to upload");//Sets the title bar text.
//Completes once the user clicks ok.
int returnVal = chooser.showOpenDialog(chooser);//
if(returnVal == JFileChooser.APPROVE_OPTION){
uploadApproval=true;
}else{
System.exit(0);
}
}
}
Class used to set directory
public void setDirectory(){//Used to set the directory.
while(saveApproval==false){//While the user does not have approval of the save location..
JFileChooser chooser2 = new JFileChooser();//Creates a new JFileChooser object.
saveFile = chooser2;//Sets the save file location to chooser2.
chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//User is only able to scan for
//directories.
//Completes once the user clicks okay.
int returnValue2 = chooser2.showDialog(chooser2, "Directory to save");
if(returnValue2 == JFileChooser.APPROVE_OPTION){
saveApproval=true;
}else{
System.exit(0);
}
}
}
Then later I begin the actual buffered reader/writer process which involves a lot of logic here:
location = "//NachaOutput"+randomNumber+".ACH";
try{
String sCurrentLine;//String representing the current line.
//Pulls the uploaded file.
br = new BufferedReader(new FileReader(NachaMain.uploadFile.getSelectedFile()));
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
Now here is what I need to do. I have been asked to remove the screen where the user selects the directory from the beginning. Instead, the user will select the save directory in the end of the process.
This means that the "SetDirectory" method won't be called at all, therefore this line of code:
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
obviously won't work. I need to find some way to replace that file writer location with a generic location that would be the same for all users regardless of their setup. Something along the lines of documents.
I tried doing this:
bw = new BufferedWriter(new FileWriter("Libraries\\Documents"+location));
but got an exception about an invalid path.
So please help me out and let me know a good path that I could save the file to automatically. That saved file will basically be a "dummy" file. Later in the end of the program I will copy that dummy file to the location the user specifies then delete it, so the location really doesn't matter too much.
Thanks in advance!
You could create a temporary file using File.createTempFile(). It might make cleanup easier if you called deleteOnExit() for the created temporary file.
Related
i got a problem with my code. First of all, i created a JfileChooser, to save my bufferedImage into a file.
The problem is when i save it, if i don't write the extension in the window it will be a normal file instead of a jpg/png or other.. How can i do that?
I tryed some weird code like getting the description of fileextension but it doesn't work
JFileChooser savechooser = new JFileChooser();
savechooser.setFileFilter(new FileNameExtensionFilter("JPEG File", "jpg"));
savechooser.setFileFilter(new FileNameExtensionFilter("PNG File", "png"));
savechooser.setFileFilter(new FileNameExtensionFilter("GIF File", "gif"));
int returnVal = savechooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
ImageIO.write(bImage, "png" , new File(savechooser.getSelectedFile().getAbsolutePath()));
I expect a "test.png" or "test.jpeg", but the actual output would be a "test" file..
The second parameter to ImageIO.write(...) ("png" in your code) is the format of the file. This is not directly related to the name of the file. A "file extension" or suffix is simply part of the name of a file, and may be anything, although by convention it is used to indicate the format of the file (ie. nothing stops you from naming a JPEG file "foo.gif" if you really want to, and it is still a JPEG file). Windows typically uses this convention to determine file type and select the appropriate application to open the file though, so using a non-standard extension may be confusing.
To fix the the problem you see, it's probably best to make sure that filename ends with the correct extension, unless the user added one. For example (assumes the user chose PNG format, but you can easily adapt it to other formats as well):
// JFileChooser code as is
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = savechooser.getSelectedFile();
String fileName = file.getName();
if (!fileName.toLowerCase().endsWith(".png")) {
file = new File(file.getParent(), fileName + ".png");
}
if (!ImageIO.write(image, "PNG" , file)) {
// TODO: Handle file could not be written case
}
}
The above will make sure the file has the correct file extension, unless the user supplied it himself.
I also see another problem in your code. You invoke savechooser.setFileFilter(..) three times. Each invocation will replace the current filter with the new one. You probably want to use savechooser.addChoosableFileFilter(...) instead (and perhaps setFileFilter(..) for the one you want to use as default). The filter will filter the files shown in the dialog, and thus what files the user clicks on, but does not impact the name the user supplied himself. You can get the current filter from savechooser.getFileFilter(), and use that to determine the format to use.
Here's a more complete solution:
JFileChooser savechooser = new JFileChooser();
FileNameExtensionFilter pngFilter = new FileNameExtensionFilter("PNG File", "png")
savechooser.addChoosableFileFilter(pngFilter);
savechooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG File", "jpg"));
savechooser.addChoosableFileFilter(new FileNameExtensionFilter("GIF File", "gif"));
savechooser.setFileFilter(pngFilter); // Default choose PNG
int returnVal = savechooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = savechooser.getSelectedFile();
FileNameExtensionFilter currentFilter = (FileNameExtensionFilter) savechooser.getFileFilter();
String ext = currentFilter.getExtensions()[0];
if (!currentFilter.accept(file)) {
// File does not not have the correct extension, fix it
String fileName = file.getName();
file = new File(file.getParent(), fileName + "." + ext);
}
String format = "jpg".equals(ext) ? "JPEG" : ext; // May not be strictly necessary, just a reminder that file ext != file format
if (!ImageIO.write(image, format , file)) {
// TODO: Handle file could not be written case
}
}
I have a simple JavaFX window with a TextField for users to enter a file path and a separate browse link.
JavaFX Window
I'd like to ask how to extract the full file path of the selected file from JavaFX FileChooser (so I can set the path in the TextField)?
I understand what I'm trying to achieve can be done simply with Swing JFileChooser with something like:
JFileChooser chooser = new JFileChooser();
String someString = chooser.getSelectedFile().toString();
But since my application is in JavaFX I want it to have a consistent look and not a mix with Swing.
I've looked through the documentation, there doesn't seem to be a method for this https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html
Thanks in advance.
Here's another documentation. What you get in return from using showOpenDialog is a File object.
public File showOpenDialog(Window ownerWindow)
Shows a new file open dialog. The method doesn't return until the
displayed open dialog is dismissed. The return value specifies the
file chosen by the user or null if no selection has been made. If the
owner window for the file dialog is set, input to all windows in the
dialog's owner chain is blocked while the file dialog is being shown.
A file object has various methods like e. g. getAbsolutePath.
Use showOpenDialog or showSaveDialog (depending on whether you want to open an existing file or save a new one). Both return a File object.
In the controller class where you have the TextField you can create a method like so:
public void getTheUserFilePath() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Upload File Path");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("ALL FILES", "*.*"),
new FileChooser.ExtensionFilter("ZIP", "*.zip"),
new FileChooser.ExtensionFilter("PDF", "*.pdf"),
new FileChooser.ExtensionFilter("TEXT", "*.txt"),
new FileChooser.ExtensionFilter("IMAGE FILES", "*.jpg", "*.png", "*.gif")
);
File file = fileChooser.showOpenDialog(dialogPane.getScene().getWindow());
if (file != null) {
// pickUpPathField it's your TextField fx:id
pickUpPathField.setText(file.getPath());
} else {
System.out.println("error"); // or something else
}
}
I am writing a notepad app and I'm making a create a password screen pop up until you've created one, and then a log in screen will pop up from then on.
Here is some sample code:
File myFile = new File(getFilesDir() + "pass.txt");
if (!myFile.exists()) // if "pass.txt" DOESN'T exist, make them create a password
{
try {
// this writes the password to the "pass.txt" file
// which is the one that is checked to exist.
// after it is written to, it should always exist.
FileOutputStream fos = openFileOutput("pass.txt", Context.MODE_PRIVATE);
fos.write(pass.getBytes());
// this writes the security question to a different file.
fos = openFileOutput("securityQ.txt", Context.MODE_PRIVATE);
fos.write(secQ.getBytes());
// this writes the security answer to a different file.
fos = openFileOutput("securityAnswer.txt", Context.MODE_PRIVATE);
fos.write(secAns.getBytes());
fos.close();
} catch(Exception e) {}
^ That is in one method. Then, in another I do this:
try { // input the right password to the String data
char[] inputBuffer = new char[1024];
fIn = openFileInput("pass.txt");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
isr.close();
fIn.close();
}catch(IOException e){}
if (password.getText().toString().equals(data)) // if password is right, log in.
{
loggedin();
}
else // if the password entered is wrong, display the right one.
{
TextView scr = (TextView)findViewById(R.id.display);
scr.setText("." + data + "."+'\n'+"." + password.getText().toString() + ".");
}
The problem is that the user can't log in even though the password is entered correctly and the display proves that.
The other problem is that whenever I run the app again, it goes to the create screen, which means that it is recognizes the file to NOT exist (even though I just wrote to it).
I've dealt with files this whole project and it can keep track of entered text so that when you press a button, it reads the file back to you. Even if you close it, it keeps track of what you input. For some reason though, the password thing doesn't work.
Here is an image of what happens (the first .k. is the data read from the "pass.txt" file and the second .k. is the user inputted String from the EditText):
SOLUTION to the logging in problem:
String values look the same but don't ".equals()" each other
Had to simply use the .trim() method on the password user input.
I'll pass on commenting about saving passwords in a file called "pass.txt", and just focus on the technical part.
File myFile = new File(getFilesDir() + "pass.txt");
myFile will never be a valid file. You don't have a separator / between the path and the file name. Since that will never be vaild, the next line will say it doesn't exist and go through the whole block.
You can easily fix this one of two ways:
File myFile = new File(getFilesDir() + "/pass.txt");
That simply adds the separator to the file name.
File myFile = new File(getFilesDir(), "pass.txt");
This is probably the better option, since it uses the explicit path, file constructor. Either one is fine, though.
You can also just use context.openFileInput("pass.txt"); and catch if FileNotFoundException occurs, at which point you can "assume" the file actually doesn't exist.
How to save a file if it is already opened without opening the FileChooser dialog like notepad ?
It took me so much time to figure out. I've searched the net but could not find something could help me here.
Thanks in Advance
My issue is in the code below. The new edit is not saved. I opened the same file and nothing was saved (not updated I mean)
fileWriter = new BufferedWriter(new
FileWriter(openFile.getSelectedFile().getPath()));
private class FileAction implements ActionListener{
public void actionPerformed(ActionEvent e){
//JOptionDialog
JFileChooser openFile = new JFileChooser();
openFile.setFileFilter(new txtFilter());
if(e.getSource() == open ){
int openOption = openFile.showOpenDialog(frame);
textArea.setText(""); //clearing the Text_AREA before opening the new file
try{
Scanner scan = new Scanner(new FileReader(openFile.getSelectedFile().getPath()));
while(scan.hasNext())
textArea.append(scan.nextLine() + "\n");
}catch(Exception ex){
//ShowDialogBox dialogBox = new ShowDialogBox();
JOptionPane.showMessageDialog(frame,"Please choose .txt File only");
}
}
} else if( e.getSource() == save){ //SAVE_BUTTON
try{
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(openFile.getSelectedFile().getPath())); //(This does not save at all I opened the file again and still as it was before editing)
fileWriter.write(textArea.getText());
fileWriter.close();
}catch(Exception ex){
}
}
}
}
Without knowing more, I assume you get a NullPointerException since when save (it is a button, right?) is pressed, the action creates a new JFileChooser instance which hasn't a selected file yet.
So you should store the selected file when it is opened in an instance variable (use openFile.getSelectedFile() in the open branch) and pass that file handle to the FileWriter that is created in the save branch.
If you're reusing the same instance of FileAction you could put the reference there, otherwise you could put it somewhere else (maybe some container object that is passed to the action) where multiple instances of FileAction have access to.
Just a word in advance: do resist the temptation to use a static variable, that's not an appropriate usage of statics.
Not related to your problem but you should NOT be using fileWriter.write(...).
Instead you should be using textArea.write(...). See Text and New Lines for more information.
I have written a Java program that opens all kind of files with a JFileChooser. Then I want to save it in another directory with the JFileChooser save dialog, but it only saves an empty file. What can I do for saving part?
Thanks.
JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.
E.g.
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(contents);
// etc...
}
Edit:
Assuming that you simply have a source file and destination file and want to copy the contents between the two, I'd recommend using something like FileUtils from Apache's Commons IO to do the heavy lifting.
E.g.
FileUtils.copy(source, dest);
Done!
Just in addition to Kris' answer - I guess, you didn't read the contents of the file yet. Basically you have to do the following to copy a file with java and using JFileChooser:
Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
Select the target file with the FileChooser. This again returns a File object
Use a FileWriter with the target File to store the String or byte array from above to that file.
The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.
Something like..
File file = fc.getSelectedFile();
String textToSave = mainTextPane.getText();
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(file));
writer.write(textToSave);
JOptionPane.showMessageDialog(this, "Message saved. (" + file.getName()+")",
"ImPhil HTML Editer - Page Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{ }