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:
}
Related
I need help regarding my java GUI, I have a jform to add movie details into a textfile add movie into textfile
when I add the data and click the save button it will automatically print on the textfile file that has been declared inside the code.
now I am creating another jform to display a specific data that has inside the textfile into a jtextfield. However, I can't seem to have any idea on how to do it. can anyone guide me through this?
display textfile into jtextfield
This is my code to display the added movie into the jtable
float subPrice,totalPrice,tax;
int stockqty = Integer.parseInt(stock.getText());
float priceUnit = Float.parseFloat(unitP.getText());
subPrice = priceUnit*stockqty;
tax = (float) (subPrice*0.60);
totalPrice = subPrice+tax;
MovieInventory.AddRowToJTable(new Object[]{
movieID.getText(),
movieName.getText(),
yearR.getText(),
language.getText(),
genre.getSelectedItem(),
rated.getSelectedItem(),
duration.getText(),
type.getSelectedItem(),
stock.getText(),
unitP.getText(),
subPrice,
totalPrice,
});
JOptionPane.showMessageDialog(this, "Movie Add Succesfully!");
}
For the save button this is my code to save the data that has been put inside jtable into the textfile.
String filePath = "/Users/finatasha/Documents/inventoryMovie.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i <jTable1.getRowCount(); i++){
for(int j=0; j< jTable1.getColumnCount(); j++){
bw.write(jTable1.getValueAt(i, j).toString()+" ,");
//using comma to seperate data
}
bw.newLine();
}
bw.close();
fw.close();
JOptionPane.showMessageDialog(this, "Data save to textfile successfully!");
} catch (IOException ex) {
Logger.getLogger(MovieInventory.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "ERROR!");
}
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.
So I'm coding a program in Java that allows me to create teams (also remove them and edit them).
After creating a team the program enables the user to add 10 players, define their weight and tries scored and once again remove and edit them. Now as soon as they reach 10 players they lose the ability of adding more and a save button is enabled.
The problem I'm having is: if I save a team and then edit it or remove it and I try to save it again, the table creates another column and moves all the values one column to the right. The images will illustrate a bit better what I mean.
When saved for first time:
After saving 2nd time:
The code for the saving function is at follows:
private void btn_SaveTeamActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel pattern = (DefaultTableModel) table_PlayerBoard.getModel();
try {
saveTable((String) table_LeaderBoard.getValueAt(table_LeaderBoard.getRowCount() - 1, 0));
} catch (Exception ex) {
Logger.getLogger(Mainpage.class.getName()).log(Level.SEVERE, null, ex);
}
enableTeamEdit();
btn_SaveTeam.setEnabled(false);
JOptionPane.showMessageDialog(null, "Team Saved");
pattern.setRowCount(0);
btn_RankTeams.setEnabled(true);
counter = 0;
}
ArrayList <Integer> triesList = new ArrayList();
ArrayList <String> teamList = new ArrayList();
boolean check = false;
I can't really understand where is the mistake. If there is any more information needed let me know. Thanks in advance.
saveTable method:
public void saveTable(String fileName)throws Exception {
DefaultTableModel chart = (DefaultTableModel) table_PlayerBoard.getModel();
BufferedWriter bfw = new BufferedWriter(new FileWriter("C:\\Users\\" + System.getProperty("user.name") + "\\Desktop\\Sports\\" + fileName + ".txt"));
System.out.println(fileName);
for (int i = 0 ; i < chart.getRowCount(); i++)
{
for(int j = 0 ; j < chart.getColumnCount();j++)
{
bfw.write((chart.getValueAt(i,j).toString()));
bfw.write("\t");;
}
bfw.newLine();
}
bfw.close();
}
In your saveTable(...) method, simply delete the contents of the given file, then open a new one for writing like this:
String path = "C:\\Users\\" + System.getProperty("user.name") + "\\Desktop\\Sports\\" + fileName + ".txt";
File file = new File(path);
file.delete();
file = new File(path);
BufferedWriter bfw = new BufferedWriter(new FileWriter(file));
My app records sounds. Once the sound is recorded, user is asked to input a new file name. Now what I'm trying to do next is to add all file names in a text file so that I can read it later as an array to make a listview.
This is the code:
//this is in onCreate
File recordedFiles = new File(externalStoragePath + File.separator + "/Android/data/com.whizzappseasyvoicenotepad/recorded files.txt");
if(!recordedFiles.exists())
{
try {
recordedFiles.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//this executes everytime text is entered and the button is clicked
try {
String content = input.getText().toString();
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(">" + content + ".mp3");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Now the problem is that everytime I record a new file, the previous line is overwritten. So if I record two files 'text1' and 'text2', after I've recorded text1, the txt file will show text1, but after I recorded the text2, the text2 will overwrite the text1 instead of inserting a new line.
I tried adding:
bw.NewLine()
before
bw.write(">" + content + ".mp3");
but it doesn't work.
If I record three sounds and name them sound1, sound2 and sound3, I want this to be the result:
>sound1
>sound2
>sound3
Use FileWriter constructor with boolean append argument
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
// ^^^^
this will let file append text at the end instead overwriting previous content.
You can do it by adding line.separator Property
bw.write(">" + content + ".mp3");
bw.write(System.getProperty("line.separator").getBytes());
Replace
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile());
Instead of
FileWriter fw = new FileWriter(recordedFiles.getAbsoluteFile(), true);
FileWriter takes a boolean if it should overwrite. So use true if you would like to to append to the file instead of overwrite.
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.