I'm trying to save and load .txt files on my program. I've got methods to read and write the files, but I want the user to be able to choose which name and where the files will be saved using the open/save forms. I've done this so far.
JButton btnLoad = new JButton("Carregar");
btnCarregar.addActionListener(new ActionListener() {
private Component modalToComponent;
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
}
}
});
Right, this actually opens the form, but after that, I don't know where and how use my methods to load the text. I guess, I should use file since it's the selected file, but when I send this file to my methods, it just doesnt work. Any example would be appreciated. Thanks before hand!
You can call a method from the point where the user has selected a file to open (in the if part of the actionPerformed method). So if your reading method is called openFile and accepts a File parameter, you can call 'openFile(file)` as the second statement in your if block:
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
openFile(file);
}
A simple example of an openFile method to handle opening a file (in this case by only printing the contents) could look like this:
private void openFile(final File inputFile) {
try (final BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line: " + line);
// todo: handle line.
}
} catch (final IOException e) {
e.printStackTrace();
// todo: handle exception.
}
}
Related
I am using Netbeans on OS X and cannot seem to write text to a text file that I have in a package named "assets".
Below is the way I tried to accomplish writing to the text file and so far my method of doing this is not working.
The way I tried to approach this problem was converting a string to url, then converting the url to a uri. Then I used the uri for the new file parameter. After I tried to write a string using the class print writer.
public class Experiment {
File createFile(String path) {
java.net.URL url = getClass().getResource(path);
URI uri;
try {
uri = url.toURI();
}
catch (URISyntaxException e) {
uri = null;
}
if ((url != null) && (uri != null)) {
System.out.println("file loading sucess");
return new File(uri);
}
else {
System.out.println("Error file has not been loaded");
return null;
}
}
File file = createFile("/assets/myfile.txt");
public static void main(String[] args) {
Experiment testrun = new Experiment();
try {
PrintWriter writer = new PrintWriter(new FileWriter(testrun.file));
writer.println("it works");
writer.flush();
writer.close();
System.out.println("string was written");
}
catch (IOException e) {
System.out.println("there was an error while writing");
}
}
}
The output given from my try catch statements say that the file write code was executed.
file loading sucess
string was written
BUILD SUCCESSFUL (total time: 2 seconds)
I have also tried using absolute string paths for making a new file, but with null results. I am running out of ideas and hoping for some guidance or solution from somebody.
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..
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
I want to read a file using jFileChooser. jFileChooser will come up after press of a button (say jbutton1ChooseFile) and select the required file. After the selection is complete, another button (say jbutton2) will be used to read the contents of the file which has just been selected by the user. So on clicking on jbutton2, selected file will be read.
I am posting few lines of code so that it would be easy to understand what I mean to say:
private void jButton1ChooseFileChooseFileActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser loadFile= new JFileChooser();
loadFile.setApproveButtonText("Select File");
loadFile.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter f1 = new FileNameExtensionFilter("Text Files", "txt", "text","rtf","doc","docx");
loadFile.setFileFilter(f1);
switch (loadFile.showOpenDialog(EncDecApp.this))
{
case JFileChooser.APPROVE_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Selection Successfull!",
"Attention!",
JOptionPane.OK_OPTION);
jButton1ChooseFile.setText("File Chosen");
jLabelChooseFile.setText(String.valueOf(loadFile.getSelectedFile()).substring(0,30)+"...");
fileSelect=true;
break;
case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "No file chosen",
"Attention!",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Error",
"Choosing File",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
}
loadFile.setVisible(true);
}
Upto this it's working perfectly.
Now, the code for jButton2 is as follows:
private void jButton2EncryptEncryptActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Charset charset=Charset.forName("UTF-8");
int returnVal=loadFile.showOpenDialog(jLabel1);
if(returnVal==loadFile.APPROVE_OPTION)
{
File filePath = loadFile.getSelectedFile();
try{
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
jTextArea1.append(line + "\n");
}
in.close();
}
catch(IOException ex)
{
System.err.println("Open plaintext error: "+ex);
}
}
}
Any help will be highly appreciated.
At first glance the problem appears to be that you are using a local variable for the JFileChooser. That is to say, you have the line:
JFileChooser loadFile= new JFileChooser();
In your jButton1ChooseFileChooseFileActionPerformed function, and yet also try to refer to loadFile in your jButton2EncryptEncryptActionPerformed function.
In order to have the loadFile object available to both you need to have said loadFile object be a member of the class to which both functions belong.
I had posted a question in regards to this code. I found that JTextArea does not support the binary type data that is loaded.
So my new question is how can I go about detecting the 'bad' file and canceling the file I/O and telling the user that they need to select a new file?
class Open extends SwingWorker<Void, String>
{
File file;
JTextArea jta;
Open(File file, JTextArea jta)
{
this.file = file;
this.jta = jta;
}
#Override
protected Void doInBackground() throws Exception
{
BufferedReader br = null;
try
{
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while(line != null)
{
publish(line);
line = br.readLine();
}
}
finally
{
try
{
br.close();
} catch (IOException e) { }
}
return null;
}
#Override
protected void process(List<String> chunks)
{
for(String s : chunks)
jta.append(s + "\n");
}
}
You could cover the most by sniffing the mime type based on the file extension or, even better, the actual file content. You can do that with help of among others jMimeMagic (Maven coords here). If the mime type does not start with "text", then it's certainly not a text file.
String mimeType = Magic.getMagicMatch(file, false).getMimeType();
boolean text = mimeType.startsWith("text");
I found that MIME types can really help with this!
JAF
For those who read this and are curious as to what I have done to fix the File reading problem.... I have instead implemented a FileReader and have experienced no problems on Windows. I have however noticed on Linux that there are some problems which tends to lead to a crash. Also I noticed when running through an IDE such as Netbeans I receive various runtime errors when trying to load a binary file and massive slow-down; but when I execute the .jar as an executable and not from the IDE it works fine.
Here is relevant code that I have had no problem with (even when loading binary file types such as .mp3, .exe, etc.)
/*...*/
#Override
protected Void doInBackground() throws Exception {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
int ch = br.read();
while(ch != -1) {
publish(ch);
ch = br.read();
}
}
finally {
try {
br.close();
} catch (IOException e) {}
}
System.gc();
return null;
}
/*...*/