Writing to a text file using Java gets cut short - java

I have a program reading from a text file (currently 653 lines long) all separated by a comma. But when I go to save the file to a new location, it only saves 490 lines. It also seems that the last line in the newly created text file is cut in half. Any ideas on what might be the problem?
Here is the code that I used to open and sort the data in the list:
try {
scanner = new Scanner(file);
// Put the database into an array and
// Make sure each String array is 13 in length
while (scanner.hasNext()) {
line = scanner.nextLine();
word = line.split(",");
if (word.length < 13) {
String[] word2 = {"","","","","","","","","","","","",""};
for (int i = 0; i < word.length; i++) {
word2[i] = word[i];
}
dataBaseArray.add(word2);
}
else {
dataBaseArray.add(word);
}
}
}
catch (FileNotFoundException exc) {
JOptionPane.showMessageDialog(this, "File cannot be found.", "error finding file", JOptionPane.ERROR_MESSAGE);
}
// Splitting the database into vacant numbers/dead lines/vacant cubicles
for (int i = 0; i < dataBaseArray.size(); i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
vacantNums.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
deadLines.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
vacantCubs.add(dataBaseArray.get(i));
}
else if (dataBaseArray.get(i)[7].equals("")) {
people.add(dataBaseArray.get(i));
}
else {
people.add(dataBaseArray.get(i));
}
}
// Resetting the DB Array to put the values back in it
dataBaseArray = new ArrayList<>();
// Ordering the arrays I want them to appear in the list
// Orering the people to appear in alphabetical order
Collections.sort(people, new Comparator<String[]>() {
#Override
public int compare(String[] strings, String[] otherStrings) {
return strings[7].compareTo(otherStrings[7]);
}
});
// Put the people in the DB Array
for (int i = 0; i < people.size(); i++) {
dataBaseArray.add(people.get(i));
}
// Put the vacant numbers in the AB Array
for (int i = 0; i < vacantNums.size(); i++) {
dataBaseArray.add(vacantNums.get(i));
}
// Put the vacant cubicles in the AB Array
for (int i = 0; i < vacantCubs.size(); i++) {
dataBaseArray.add(vacantCubs.get(i));
}
// Put the dead lines in the AB Array
for (int i = 0; i < deadLines.size(); i++) {
dataBaseArray.add(deadLines.get(i));
}
list = new String[dataBaseArray.size()];
// Add the DB Array to the list
for (int i = 0; i < list.length; i++) {
if (dataBaseArray.get(i)[8].equals("VACANT")) {
list[i] = "VACANT";
}
else if (dataBaseArray.get(i)[4].equals("DEAD")) {
list[i] = "DEAD";
}
else if (dataBaseArray.get(i)[6].equals("") && dataBaseArray.get(i)[7].equals("")) {
list[i] = "Vacant Cubicle";
}
else if (dataBaseArray.get(i)[7].equals("")) {
list[i] = dataBaseArray.get(i)[6];
}
else {
list[i] = dataBaseArray.get(i)[7] + ", " + dataBaseArray.get(i)[6];
}
}
// Populate the list
lstAdvance.setListData(list);
Here is what I used to save the file:
try {
saveFile = new FileWriter("Save Location");
String newLine = System.getProperty("line.separator");
for (int i = 0; i < dataBaseArray.size(); i++) {
for (int j = 0; j < dataBaseArray.get(i).length; j++) {
saveFile.append(dataBaseArray.get(i)[j] + ",");
}
saveFile.append(newLine);
}
}
catch (IOException exc) {
JOptionPane.showMessageDialog(this,"error", "error", JOptionPane.ERROR_MESSAGE);
}

Writing to a file is buffered. You have to close() or flush() your writer (saveFile) at the end of writing.
Even better: you should do close() on your writer in the finally block.

Try it using the FileWriter and BufferedWriter....
File f = new File("Your_Path");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
And yes..its very important to do bw.close() (Closing the Buffer)

See this question : Java FileWriter with append mode
The problem is that your FileWriter object needs to be "append mode" . Then, you append to the file with the "write" method rather than the "append" method. Use a finally catch clause to call "close" . You don't need to flush ( I dont think).

Related

Trying to copy data from a file to an array but it gives me error

Hi I am new on programing and I am having a problem I am trying to copy some things from a file to a array
and I just want to copy in the position 1,2,3 and 4 from the file. Example copy to the array 11 , G , 0 , 20.
FILE TEXT:
0;11;G;0;200;1
2;10;F;0;300;2
0;12;J;0;100;3
String[][] aa = new String[100][6];
try {
Scanner x = new Scanner(new File("Turmas.txt"));
x.useDelimiter("[;\n]");
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 6; j++) {
if (x.hasNext()) {
aa[i][j] = x.next();
}
}
}
x.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
String[][] aaa = new String[100][4];
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 4; j++) {
if (aa[i][j] == null) {
System.out.println("null " + i + " " + j);
}
else {
if (aa[i][0].equals(String.valueOf(SAVEID))) {
aaa[i][j] = aa[i][1];
aaa[i][j + 1] = aa[i][2];
aaa[i][j + 2] = aa[i][3];
aaa[i][j + 3] = aa[i][4];
}
}
}
}
System.out.println(aaa[0][0]);
System.out.println(aaa[0][1]);
System.out.println(aaa[0][2]);
System.out.println(aaa[0][3]);
If only 4 values are needed from the input array are needed, why not just read these specific values?
String[] result = new String[4];
try (Scanner input = new Scanner(new File("Turmas.txt")) // input closed automatically
.useDelimiter(";|\\R") // use character class \R to match line-feed characters
) {
if (input.hasNext()) {
input.next(); // skip the 1st token
for (int i = 0; i < result.length && input.hasNext(); i++) {
result[i] = input.next();
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
If it is needed to read the columns with indexes [1..4] from the file containing 6 columns per line, it is cleaner to read the source file line by line, split each line by ;, skip 1 column with index 0, and keep the 4 columns.
String[][] result = new String[100][4];
try (Scanner input = new Scanner(new File("Turmas.txt"))) {
for (int i = 0; i < result.length && input.hasNextLine(); i++) {
String[] parts = input.nextLine().split(";");
for (int j = 1; j < Math.min(result[i].length, parts.length); j++) {
result[i][j - 1] = parts[j];
}
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(
null, "An error occurred, try restarting the program!",
"ERROR!", JOptionPane.ERROR_MESSAGE
);
}
This loop:
for(int j=0;j<4;j++)
runs again with a value of j = 1 after it completes the first iteration, so when it gets to the expression aaa[i][j+3] the second index evaluates to 4, which of course is illegal. I'm not sure why you used a for loop there, since you manually increment the index values as you assign the aaa values?

How to append only one line/row for each iteration in appending values to CSV file in Java

I am having some issues in terms of appending data into my CSV file. The problem is that whenever I try to append data into my CSV file on a second time, the second value which is appended to the CSV file comes with the first appended value. It's like it brings the existing value with it when appending to the CSV file. Thus, because of this issue, it results into an array index out of bounds exception in this statement: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; , the data of the CSV file repeats the existing values along with the latest appended values and also the first value is only displayed on my GUI table.
CSV File:
Table:
Here's my source code in writing and reading the CSV:
public void writeCustomerCSV(){ // this creates a CSV file which stores the inputs of the user
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv",true)); // when I set append mode to true, cust[read2DStringIndex][newVarIndexer] = fromfile[g] results to index array out of bounds to 10
StringBuilder sb = new StringBuilder();
int y;
for(int x = 0; x < itemTo2D.length; x++){
if(itemTo2D[x][0] != null){
for(y = 0; y < itemTo2D[0].length; y++){
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
}
catch (Exception ex){
}
}
public void readCustomerCSV(){ // reads the contents of the CSV file
String[][] twoDArray = new String[10][7];
int read2DStringIndex = 0;
int newVarIndexer = 0;
DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel(); // table
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
int ak = 0;
int sk = 0;
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null){
fromfile = line.split(","); //separates the columns by a comma
for(int c = 0; c < fromfile.length; c++){
if(fromfile[c].equals("-")){
sk = 0;
ak++;
if(c > 0){
if(!fromfile[c-1].equals("-")){
id = id + 1;
}
}
} else{
twoDArray[ak][sk] = fromfile[c];
sk++;
}
}
}
} catch (Exception ex){
}
for(int g = 0; g < fromfile.length; g++){
if(fromfile[g].equals("-")){ //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
newVarIndexer = 0;
}
else{
cust[read2DStringIndex][newVarIndexer] = fromfile[g]; //cust is the 2D array(declared universal) which is going to display the values to the table
newVarIndexer++;
}
}
for(int h = 0; h < cust.length; h++){ //prints cust (2D array) , just to check what data is being stored
for(int p = 0; p < cust[0].length; p++){
System.out.println(cust[h][p] + ",");
}
}
setrowcount = 0;
for(int r = 0; r < cust.length; r++){
if(setrowcount == 0){
tblmodelll.setRowCount(0);
}
try{
if(cust[r][0].equals("null") == false){
tblmodelll.addRow(cust[r]); //displays the cust(2D array) data to table
}
} catch(Exception e){
}
setrowcount++;
}
}
Is there something missing in my structure of the codes or is my logic in appending the values not right?
Your responses would indeed help me in resolving this issue.
Thank you very much.

How to print in file array

Soo, I have to insert list of arrays into a specific text document.
The array list is inset by user at case 1 and it works well.
When I try call case 4 without any data, the file is created and also it's empty.
When I do this with an array list I get the Error message from catch.
How can I fix it?
Here is the call to function.
case 4: System.out.println("\nLungimea dintre doua orase alaturate\n");
try{
System.out.println("oabdobasoda");
salvareOras();
}catch (Exception e){
System.out.println("Eroare");
}
and here is the function.
public static void salvareOras()
{
for(int i = 0; i<drum.size()-1; i++){
for(int j = 0; i<drum.size(); j++){
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
try {
FileOutputStream fOut = new FileOutputStream("distante.txt");
PrintStream ps = new PrintStream(fOut);
for(int i = 0; i <drum.size()-1; i++){
ps.println("d(" + drum.get(i).getNume()+","+drum.get(i+1).getNume()+")="+distOras(drum.get(i), drum.get(i+1)));
}
ps.close();
fOut.close();
} catch(IOException ex){
System.out.println("Nu s-a putut crea fisierul");
System.exit(1);
}
}
You made a minor mistake in your 2nd for loop:
for(int i = 0; i<drum.size()-1; i++){
//specifically on this line here:
for(int j = 0; i<drum.size(); j++){
//^//That is not j
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
//that means ^ will throw an IndexOutOfBoundsException
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}
Just change it to:
for(int i = 0; i<drum.size()-1; i++){
for(int j = 0; j<drum.size(); j++){
//^ j
if(drum.get(i).getPozitie() > drum.get(j).getPozitie()){
Oras aux = drum.get(i);
drum.add(i, drum.get(j));
drum.add(j, aux);
}
}
}

Why can my program not find a file after saving it

I am working on an inventory program and keep running into an issue. I have some text files that are named using a combination of numbers. I call them shelves. I open them up and edit them to store items in them. I am having a problem after I remove some objects from one of these.
How that process goes is I will open the file. Load it into a JTable. Select the item and amount I wish to remove. Then re save the file. That all works great until I go to open another shelf. Any other shelf I try to open after that process tells me that the shelf does not exist even if it the same one I just used. I can still go through the path on my computer and find it just fine and I can close the program and reopen it and it works just fine again until I remove and item from the shelf. I will post any relevant code below. Thanks for the help guys.
String[] binCombos = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
JComboBox<String> aisle, column, row;
JButton open = new JButton("Open Shelf");
tableHolder = new JScrollPane(shelfsContents);
aisle = new JComboBox<String>(binCombos);
column = new JComboBox<String>(binCombos);
row = new JComboBox<String>(binCombos);
open.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
shelfCombo = aisle.getSelectedItem().toString() + column.getSelectedItem().toString() + row.getSelectedItem().toString() + ".txt";
File shelfName = new File(sPath + "\\" + shelfCombo);
if(shelfName.exists() == true && Console.console.IsPulling() == false)
{
OpenShelf(shelfName);
}
else
{
System.out.println(shelfName + " does not exist");
}
}
});
private void SaveShelf()
{
try
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
bfw.write(tableModel.getValueAt(i, j).toString());
bfw.write(" : ");
}
}
}
bfw.newLine();
}
bfw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try this code
private void SaveShelf(){
PrintWriter pw ;
try
{
pw = new PrintWriter(new File("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
pw.print(tableModel.getValueAt(i, j).toString());
pw.print(" : ");
}
}
}
pw.println();
pw.flush();
}
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
pw.close();
}
}

Unable to open file using File f = new File(file_pth);

I am trying to open a file by drag and drop onto JTextField but i always get the error.
Heres my code
public void drop(DropTargetDropEvent dtde) {
String str4=null;
try {
JTextArea comp = null;
if(Switchtab==2)
comp=textarea1;
if(Switchtab==3)
comp=textarea2;
if(Switchtab==4)
comp=textarea3;
if(Switchtab==1)
comp=textarea4;
// Ok, get the dropped object and try to figure out what it is
Transferable tr = dtde.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
for (int i = 0; i < flavors.length; i++) {
System.out.println("Possible flavor: "
+ flavors[i].getMimeType());
// Check for file lists specifically
if (flavors[i].isFlavorJavaFileListType()) {
// Great! Accept copy drops...
dtde.acceptDrop(DnDConstants.ACTION_COPY);
// comp.setText("Successful file list drop.\n\n");
// And add the list of file names to our text area
java.util.List list = (java.util.List) tr
.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
//wcomp.append(list.get(j) + "\n");
str4=list.get(j)+"\n";
}
// Replace '\' with '/'
file_pth = str4.replaceAll("\\\\","/" );
System.out.println(str4.replaceAll("\\\\","/" ));
//Open the file
try {
File f = new File(file_pth);
FileInputStream fobj = new FileInputStream(f);
int len = (int) f.length();
str4 = "";
for (int j = 0; j < len; j++) {
char str5 = (char) fobj.read();
str4 = str4 + str5;
}
comp.setText(str4);
setTitle(str4);
} catch (Exception e) {
System.out.println("Caught::" + e);
}
// If we made it this far, everything worked.
dtde.dropComplete(true);
return;
}
}
// Hmm, the user must not have dropped a file list
System.out.println("Drop failed: " + dtde);
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
I even tried replacing backslash with double backslash and forward slash but still i get this error
Possible flavor: application/x-java-file-list; class=java.util.List
C:/kevin_java/file io/DemoIO.java
Caught::java.io.FileNotFoundException: C:\kevin_java\file io\DemoIO.java
(The filename, directory name, or volume label syntax is incorrect)
The output doesnt show the replaced string.
It shows the previous string with single backslash.
finally i got my answer.
Simple solution
java.util.List list = (java.util.List) tr
.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
str4=list.get(j).toString();
}
File f = new File(str4);
FileInputStream fobj = new FileInputStream(f);
...
...
..
Edit
From the javadoc for isFlavorJavaFileListType,
Returns true if the DataFlavor specified represents a list of file objects.
Therefor,
FileInputStream fobj = new FileInputStream(list.get(list.length()-1));

Categories