Reading delimited txt file into JTable - java

I went through this tutorial to learn how to use Netbeans to create a GUI application to take information in on a form, be able to edit it, and save it to a JTable. I now want to expand what I learned to be able to write this JTable to a delimited text file and read it in at a later date to add more data. I have managed to successfully write the data to a file. The code for that is here and is executed through a menu event I created:
private void mnuSaveActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tblProduct.getRowCount(); i++) {
for (int j = 0; j < tblProduct.getColumnCount(); j++) {
bw.write((String) tblProduct.getModel().getValueAt(i, j) + "#");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
I have read many posts dealing with things such as StringTokenizer but I just can't seem to wrap my head around what approach to take. Any direction would be appreciated.
UPDATE:
#camickr: Wasn't working at first but I figured it out. I wasn't adding a "\n" when writing the file. I have updated my code and also added code to clear my Jtable when opening a new file. Let me know if there's anything that is not "good practice".
private void mnuOpenActionPerformed(java.awt.event.ActionEvent evt) {
String line;
DefaultTableModel model = (DefaultTableModel) tblProduct.getModel();
for (int i = tblProduct.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
model.addRow(line.split("#"));
}
br.close();
fr.close();
} catch (IOException ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
Here is what my test textfile looks like as generated:
Test1#Electronic#23.50#
Test2#Art#100.00#
Test3#Food#25.00#
Test4#Electronic#10.00#
Test5#Art#1.00#
Test6#Electricity#3.00#
Test7#Food#5.00#
Test8#Food#7.00#
Test9#Electronic#9.00#

Create an empty DefaultTableModel with your column names.
Then you can use the String.split(...) method to split each line of data.
Then you can use the addRow(...) method of the DefaultTableModel to add the data to the model.
Then can create your JTable with the DefaultTableModel.

Related

overwriting a file in java using FileWriter

I have to accomplish a task of writing a set of data to file, use it, then overwrite it with new data. Thus overwrite of the file takes place repeatedly.I know i can accomplish the above by creating FileWriter object each time with the option to overwrite like below
FileWriter object = new FileWriter("fileName", false)
and close it to write to the file.
If i am supposed to overwrite the file n number of times , according to the above method i need to create n number of FileWriter objects. Is there any efficient way to overwrite a file repeatedly by only creating a single FileWriter object?
Not a direct answer, but anyway.
DON'T DO THAT!
What do you think will happen if for some reason writing the new data to the file fails?
You not only lose your original file, but also the new file contents...
Write the new content to another file, ensure that it is well written and closed, and then rename the new file atomically to the original file.
PS: and do not forget to correctly .close().
PS2: if you use Java 7, use the new Files API.
Its better to make a temp file and then rename the tempfile and delete the old like here:
public static void nachtragenTRA(File files) throws IOException{
Scanner sc=null;
File f= files;
String analyse = "";
String NTausgabe = "";
int max = 0;
int k = 0;
String updatedLine[] = new String [4];
int filenr = 1;
boolean sucess = false;
try{
sc= new Scanner(f);
}catch(FileNotFoundException x){
System.out.println("Error: File not found!");
}
while (sc.hasNextLine()){ //get next line
analyse = sc.nextLine();
max = analyse.length(); //get line lenght
StringBuffer sb = new StringBuffer(analyse); //write analyse in StringBuffer
//to change the string
if(k == 1)
{
sb.replace(Daten.NTdatapos[3],max, Daten.NTProbentypTextfield.getText());
updatedLine[0] =String.valueOf(sb);
}
else if(k == 2)
{
sb.replace(Daten.NTdatapos[4],max, Daten.NTPrueferTextfield.getText());
updatedLine[1] =String.valueOf(sb);
}
else if(k == 3)
{
sb.replace(Daten.NTdatapos[5],max, Daten.NTKundeTextfield.getText());
updatedLine[2] =String.valueOf(sb);
}
else if(k == 4)
{
sb.replace(Daten.NTdatapos[5],max, Daten.NTWerkstoffTextfield.getText());
updatedLine[3] =String.valueOf(sb);
}
if(k>3)
{
break;
}
k++;
}
sc.close();
//NTausgabe=DatenTextarea.getText()+"\n"+updatedLine[0]+"\n"+updatedLine[1];
//DatenTextarea.setText(String.valueOf(NTausgabe));
//NTausgabe=DatenTextarea.getText()+"\n"+NTKundeTextfield.getText()+"\n"+NTPrueferTextfield.getText();
//DatenTextarea.setText(String.valueOf(NTausgabe));
//create tmp file with the new data
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(String.valueOf(f)+".tmp")));
BufferedReader br = null;
FileReader reader = null;
try {
reader = new FileReader(String.valueOf(f));
br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null)
{
//Change speciffic lines
if(filenr == 2)
{
writer.println(updatedLine[0]);
}
else if(filenr == 3)
{
writer.println(updatedLine[1]);
}
else if(filenr == 4)
{
writer.println(updatedLine[2]);
}
else if(filenr == 5)
{
writer.println(updatedLine[3]);
}
//Andere Zeilen beibehalten
else
{
writer.println(line);
}
filenr = filenr + 1;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
reader.close();
br.close();
File realName = new File(String.valueOf(f));
realName.delete(); //delete old file
writer.close();
sucess = new File(String.valueOf(f)+".tmp").renameTo(realName); //rename tmp File to the others name
if(sucess != true)
{
NTausgabe=Daten.DatenTextarea.getText()+"\n"+"Rename File failed";
Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
}
else
{
NTausgabe=Daten.DatenTextarea.getText()+"\n"+"File renamed sucessfully";
Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
}
}
}

BufferedWriter overwriting itself

I want to read in a file and create a duplicate of the file but my code only write the last line in the file. How do I make so that whenever I call write(), it writes to a new line. I want to create a new file for the duplicate so I can't add true to FileWriter constructor.
This is my code:
//Create file reader
BufferedReader iReader = new BufferedReader(new FileReader(args[1]));
//Create file writer
BufferedWriter oWriter = new BufferedWriter(new FileWriter(args[2], true));
String strLine;
//reading file
int iterate = 0;
while((strLine = iReader.readLine()) != null) {
instructions[iterate] = strLine;
}
//creating duplicate
for(int i = 0; i < instructions.length; i++) {
if(instructions[i] != null) {
oWriter.write(instructions[i]);
oWriter.newLine();
} else {
break;
}
}
try {
iReader.close();
oWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
You are not incrementing iterate
int iterate = 0;
while((strLine = iReader.readLine()) != null)
{
instructions[iterate] = strLine;
iterate++;
}
You're not updating the index of the instructions array.
In addition, it's not immediately clear why you're copying the file this way anyway; why bother doing it line-by-line? Or just use a utility class, like from Apache Commons.

Appending a text file with a 2D array

I have a method to store the input of a 2D array in a .txt file. However, even with the true put on the end of FileWriter fw = new FileWriter("CBB.dat");, something that usually allows for appending in past projects, the file still only receives one entry before writing over it with the next entry. How would this be fixed?
public void Save(String[][] EntryList)
{
try
{
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
if (EntryList[0][0] != null)
{
DataOutputStream outstream;
outstream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for (int row = 0; row < EntryList.length; row++)
{
for (int col = 0; col < EntryList[row].length; col++)
{
if (EntryList[row][col] != null) outstream.writeUTF(EntryList[row][col]);
}
outstream.close();
}
}
else System.out.print("Something is wrong");
} catch (IOException e)
{
e.printStackTrace();
}
}
Use a CharSequence instead of a String[][] (or you could also use variable arity parameters):
public static void save(CharSequence entryList)
{
BufferedReader read;
BufferedWriter write;
File file = new File("CBB.dat");
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "\n";
}
read.close();
write = new BufferedWriter(new FileWriter(file));
write.append(complete);
write.append(entryList);
write.flush();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

DefaultTableModel is saving to a file but how can I load the file to use it again?

I'm trying to save the contents of a JTable to a file and then open the file when needed to bring up the original JTable. I am using the DefaultTableModel to add rows and columns to the JTable so I decided to save my model to a file. Here is my method:
public void outputfile(DefaultTableModel model) {
String filename = "data.file";
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(model);
oos.close();
}
catch(IOException e) {
System.out.println("There was a problem creating file: " + e);
return;
}
System.out.println("JTable correctly saved to file " + filename);
}
So now that my model is saved to data.file, I have a method that opens the file. Or...that's what it's supposed to do:
public void inputfile() {
String filename = "data.file";
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
model = (DefaultTableModel)ois.readObject();
}
catch(Exception e) {
System.out.println("Problem reading back table from file: " + filename);
return;
}
}
So, in my main I simply write:
outputfile(model); //to save model to file.
inputfile(); //to extract model from file and then apply it to the table.
table = new JTable(model);
So, thank you for reading but it's not working. Nothing happens when I use inputfile. help please?
public void writefile2(JTable table) {
try{
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
TableModel model = table.getTableModel();
for(int i = 0; i<model.getRowCount(); i++) {
for(int j = 0; j<model.getColumnCount(); j++) {
out.write((String)model.getValueAt(i, j));
}
}
out.close();
}catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
This code would dump JTable to a file
TableModel model = table.getModel();
for( int i = 0; i < model.getRowCount(); i++ )
{
for( int i = 0; i < model.getColumnCount(); j++ )
{
//Create your File Writer
fileWriter.write( model.getValueAt( i, j );
}
}
In reverse direction you can call setValueAt()

Loop only deletes first file

I'm having a problem getting all the selected files deleted. What I'm trying to do is after clicking "Add" whatever files are selected are moved to a new folder and are deleted in their previous folder. One file works fine. It deletes and moves the file. But more than one and only the first gets deleted. My loop is recognizing each file just not deleting them. I'm posting the actionevent. If more code is needed let me know. I've indicated where the problem is, so I think, so you don't have to search the code.
public void actionPerformed(ActionEvent e) {
int returnValue = 0;
int option = 0;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE")) System.exit(0);
else if (e.getActionCommand().equals("ADD")) {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
returnValue = chooser.showOpenDialog(this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File[] file = chooser.getSelectedFiles();
try {
FileInputStream fstream = null;
FileOutputStream ostream = null;
for (int i = 0; i < file.length; i++) {
fstream = new FileInputStream(file[i]);
ostream = new
FileOutputStream(file[i].getName());
Path path = Paths.get(file[i].getPath());
byte[] fileArray;
fileArray = Files.readAllBytes(path);
listModel.add(0, file[i].getName());
selectedFilesList.setModel(listModel);
//ostream.write(fileArray, 0, fileArray.length);
}
fstream.close();
//ostream.close();
try {
for(int i = 0; i < file.length; i++) {
//**----------------------->>>PROBLEM**
Files.delete(Paths.get(file[i].getPath()));
System.out.println(file[i].getName());
}
} catch (NoSuchFileException x) {}
System.err.format("%s: no such" + " file or directory%n")
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n");
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
} catch (Exception err) {
}
}
This could be caused by you failing to close your file streams in the first loop.
for (int i = 0; i < file.length; i++) {
fstream = new FileInputStream(file[i]);
ostream = new
FileOutputStream(file[i].getName()); // This is never closed
Path path = Paths.get(file[i].getPath());
byte[] fileArray;
fileArray = Files.readAllBytes(path);
listModel.add(0, file[i].getName());
selectedFilesList.setModel(listModel);
//ostream.write(fileArray, 0, fileArray.length);
}
fstream.close(); // Only the last input stream is closed
should be more like
for (int i = 0; i < file.length; i++) {
try {
fstream = new FileInputStream(file[i]);
ostream = new
FileOutputStream(file[i].getName());
Path path = Paths.get(file[i].getPath());
byte[] fileArray;
fileArray = Files.readAllBytes(path);
listModel.add(0, file[i].getName());
selectedFilesList.setModel(listModel);
//ostream.write(fileArray, 0, fileArray.length);
} finally {
fstream.close();
ostream.close();
}
}
Closing the same number of files you open.
This could be causing your problem by holding a lock on all but one of your files which would prevent deletion.
Also your catch exception block (last statement) does nothing with the error.
Don't move files like that!
If you are on Java 7, have at look at this page instead.
For older versions, use oldFile.renameTo(newFile).
EDIT: To understand why your code is not working, use a debugger. I would think your deletion loop is left because of an exception.

Categories