Write multiple line on netbeans? - java

how can I write multiple lines so that I am able to record all achievements without overwriting the content? Thank you.
private void view_btnActionPerformed(java.awt.event.ActionEvent evt) {
try{
FileWriter FW = new FileWriter(""+StudRecord+"/"+LRN_Field.getText()+".txt");
System.out.print(achievement_Field.getText());
FW.write(""+achievement_Field.getText()+"");
JOptionPane.showMessageDialog(this, "Achievement Added");
achievement_Field.setText(" ");
FW.close();
}catch(Exception e){
System.out.print((e));
}
}
THE GUI IM WORKING ON

You are opening the file for writing, and your text will be the content of the file. Instead, open the file for appending.
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/FileWriter.html#%3Cinit%3E(java.io.File,boolean)

Related

Saving JTable as a textfile

Im making a medical resource management system and i am using a text file to import the first set of Doctors. This is working fine and i have added the ability to remove a selected row, which is also working. However i want this change to become permanent and save on the text.
When i press my save button on the Java GUI i just clears the entire text file. I also have the ability the add separate doctors which is also working correctly. Any help would be appreciated. Below is my code for exporting the Jtable to the text file!
private void jButtonSaveActionPerformed(java.awt.event.ActionEventevt)
{
String filePath = "C:\\Users\\Stephen\\folder\\Programming
Assignment copy\\doctor.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < jTableDoc.getRowCount(); i++){//rows
for(int j = 0; j < jTableDoc.getColumnCount(); j++){//columns
bw.write(jTableDoc.getValueAt(i, j).toString()+",");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(doctorTable.class.getName()).log(Level.SEVERE, null, ex);
} // TODO add your handling code here:
}

Java swing Save and Save as functions with JFileChooser

I am writing a little app and would like to add the same handler for two buttons: Save and Save As. For save if the file exists it should not open the JFileChooser,just save the content, but with my current code it always opens the dialog. How do I do this? Here's my code
public void actionPerformed(ActionEvent e) {
JComponent source = (JComponent)e.getSource();
if (pathToFile.length()>0){
File file = new File(pathToFile);
if (file.exists()){
try(FileWriter fw = new FileWriter(file.getName() + ".txt", true)){
fw.write(area.getText());
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
}
else{
if (fchoser.showSaveDialog(source.getParent())== JFileChooser.APPROVE_OPTION){
try(FileWriter fw = new FileWriter(fchoser.getSelectedFile()+".txt")){
fw.write(area.getText());
f.setTitle(fchoser.getSelectedFile().getPath());
pathToFile = fchoser.getSelectedFile().getPath();
}
catch(Exception ex){
}
}
}
UPDATE Added code to check if file exsists. It does and there is no exception but the additional text does not write.
Not related to your question but:
fw.write(area.getText());
Don't use the write method of a FileWriter. This will always write the text to the file using a "\n" as the line separator which may or may not be correct for the OS your code is running on.
Instead you can use the write(...) method of the JTextArea:
area.write(fw);
Then the proper line separator will be used.

How do I append text to a csv/txt file in Processing?

I use this simple code to write a few strings to the file called "example.csv", but each time I run the program, it overwrites the existing data in the file. Is there any way to append the text to it?
void setup(){
PrintWriter output = createWriter ("example.csv");
output.println("a;b;c;this;that ");
output.flush();
output.close();
}
import java.io.BufferedWriter;
import java.io.FileWriter;
String outFilename = "out.txt";
void setup(){
// Write some text to the file
for(int i=0; i<10; i++){
appendTextToFile(outFilename, "Text " + i);
}
}
/**
* Appends text to the end of a text file located in the data directory,
* creates the file if it does not exist.
* Can be used for big files with lots of rows,
* existing lines will not be rewritten
*/
void appendTextToFile(String filename, String text){
File f = new File(dataPath(filename));
if(!f.exists()){
createFile(f);
}
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
out.println(text);
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
/**
* Creates a new file including all subfolders
*/
void createFile(File f){
File parentDir = f.getParentFile();
try{
parentDir.mkdirs();
f.createNewFile();
}catch(Exception e){
e.printStackTrace();
}
}
You have to use a FileWriter (pure Java (6 or 7)) rather than PrintWriter from the Processing API.
FileWriter has a second argument in it's constructor that allows you to set a Boolean to decide whether you will append the output or overwrite it (true is to append, false is to overwrite).
The documentation is here: http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html
Note you can also use a BufferedWriter, and pass it a FileWriter in the constructor if that helps at all (but I dont think it's necessary in your case).
Example:
try {
FileWriter output = new FileWriter("example.csv",true); //the true will append the new data
output.println("a;b;c;this;that ");
output.flush();
output.close();
}
catch(IOException e) {
println("It Broke :/");
e.printStackTrace();
}
As above, this will work in the PDE - and in Android - but if you need to use it in PJS, PyProcessing, etc, then you will have to hack it
dynamically read the length of the existing file and store it in an ArrayList
add a new line to the ArrayList
use the ArrayList index to control where in the file you are currently writing
If you want to suggest an enhancement to the PrintWriter API (which is probably based off of FileWriter), you can do so at Processing's Issue page on GitHub:
https://github.com/processing/processing/issues?state=open
Read in the file's data, append your new data to that, and write the appended data back to the file. Sadly, Processing has no true "append" mode for file writing.

Opening and Writing to file Java

I'm currently stuck on a spot in my code. I need to write data to a text file, I have sorts going and they are taking the time that each sort takes to complete and then puts them into a txt file that I can then use to create graphs. Problem is that I just get one line after I run the program. I can't get it to keep each result.
public static void resultsToFile(String sort, double seconds, File file)
{
try (PrintWriter out = new PrintWriter(new FileWriter(file)))
{
out.write(sort + "\t");
out.write(seconds + " seconds\n");
out.flush();
out.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
This is what I have so far for my writing to files method. Any help would be greatly appreciated!
You're creating a new PrintWriter object each time you write a line of results to the file and thus over-writing any previously existing File that held the previous line of data. Why not create your PrintWriter once in the class, and then close it when you're done writing all of the data to file?
As HovercraftFullOfEals mentioned, you open the file for each line, and this is a big performance overhead.
Yet the problem you see is because you don't open the file to append to it, but to write to it from the beginning. To append to the file, open it using the constructor FileWriter(File,boolean):
try (PrintWriter out = new PrintWriter(new FileWriter(file, true)))

Saving already Opened File in JFileChooser Java?

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.

Categories