最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - How do I write a multi line file with Writer? - Stack Overflow

programmeradmin3浏览0评论

I had success looping through my 5 database rows and writing a CSV file, except the code that I used rewrote the file every line. I will use the CSVParser to read the file to import an activity from another computer. The examples I found online for append are few.

Can I start the Writer with append as true, or is there a better way to write the file. I used the following to write the CSV line from the String d built from the row of the database:

                try (Writer w = new OutputStreamWriter(fs.openOutputStream(String.valueOf(sendFile)))) {
                    w.write(d);
                } catch (Exception e) {
                    Log.p("Error " + e);
                }

Thanks.

Edit 1: This is the method I use to read the database into strings. Both Writer, as Shai showed me before (shown above), and writeToSting illustrated below (with \n added to the string) overwrite row 1 with row 2, etc. and at conclusion give a csv file with only row 5.

    public void toSVC(addActivity c) throws IOException, InstantiationException {
        namet = c.name.toString();
        dbsa = Display.getInstance().openOrCreate("pandr.db");
        String rd = "SELECT * FROM pandr WHERE name ='" + namet + "'";
        cursa = dbsa.executeQuery(rd);
        Row currentRow = cursa.getRow();
        cc = currentRow.getInteger(3);
        x = cc + 1;
        rn = 1;
        for (r = 1; r < x; r++) {
            trecno = rn.toString();
            tname = currentRow.getString(1);
            tpos = currentRow.getInteger(2);
            posv = tpos.toString();
            ttr = currentRow.getInteger(3);
            trv = ttr.toString();
            tbloc = currentRow.getString(4);
            tlwloc = currentRow.getString(5);
            tcfloc = currentRow.getString(6);
            trwloc = currentRow.getString(7);
            tamloc = currentRow.getString(8);
            tcmloc = currentRow.getString(9);
            tdmloc = currentRow.getString(10);
            tlcbloc = currentRow.getString(11);
            trcbloc = currentRow.getString(12);
            tlfbloc = currentRow.getString(13);
            trfbloc = currentRow.getString(14);
            tgloc = currentRow.getString(15);
            String d = trecno + "," + tname + "," + posv + "," + trv + "," + tbloc + "," + tlwloc + "," + tcfloc + "," + trwloc + "," + tamloc + "," + tcmloc + "," + tdmloc + "," + tlcbloc + "," + trcbloc + "," + tlfbloc + "," + trfbloc + "," + tgloc+"\n";
            String flname = new String("/" + namet + ".csv");
            FileSystemStorage fs = FileSystemStorage.getInstance();
            File sendFile = new File(fs.getAppHomePath() + flname);
            Util.writeStringToFile(sendFile, d);
            rn++;
        }
        dbsa.close();
        cursa.close();
        Util.cleanup(os);
        new FinishBanner();
    }
}

I first moved the Writer builder outside the loop, and tried w.write(d) for each row, but that gave me a java.lang.NullPointerException on row 2.

I also tried to use StringBuilder and sb.append(d) (with \n included at the end of the string) to the StringBuilder for the 5 rows, but sb.append(d) also gave me a java.lang.NullPointerException when trying to write the first line to the StringBuilder.

I thought the easiest way to accomplish this was create the file and append each row to the file, which is why I thought StringBuilder.append() would work. I am finding there aren't any website documents showing a way to accomplish this.

My goal is still to write a file that I can email and parse, and write into the activity database on a different device.

Edit 2 In my work to get the data order correct, I left off cursa.next(), which was why I got line 1 repeated. If I went back to my original code, Writer would work.

A new problem has manifest with this method. The StringBuilder sb has the first line twice. I increased x to 7, and the StringBuilder showed line 5 from the database as line 6 in sb.

Here is the current loop with the same head as above:

        for (r = 1; r < x; r++) {
            trecno = rn.toString();
            tname = currentRow.getString(1);
            tpos = currentRow.getInteger(2);
            posv = tpos.toString();
            ttr = currentRow.getInteger(3);
            trv = ttr.toString();
            tbloc = currentRow.getString(4);
            tlwloc = currentRow.getString(5);
            tcfloc = currentRow.getString(6);
            trwloc = currentRow.getString(7);
            tamloc = currentRow.getString(8);
            tcmloc = currentRow.getString(9);
            tdmloc = currentRow.getString(10);
            tlcbloc = currentRow.getString(11);
            trcbloc = currentRow.getString(12);
            tlfbloc = currentRow.getString(13);
            trfbloc = currentRow.getString(14);
            tgloc = currentRow.getString(15);
            sb.append(trecno).append(",")
                        .append(tname).append(",")
                        .append(posv).append(",")
                        .append(trv).append(",")
                        .append(tbloc).append(",")
                        .append(tlwloc).append(",")
                        .append(tcfloc).append(",")
                        .append(trwloc).append(",")
                        .append(tamloc).append(",")
                        .append(tcmloc).append(",")
                        .append(tdmloc).append(",")
                        .append(tlcbloc).append(",")
                        .append(trcbloc).append(",")
                        .append(tlfbloc).append(",")
                        .append(trfbloc).append(",")
                        .append(tgloc).append(",")
                        .append("\n");
            rn++;
            cursa.next();
        }

I am going to reconstruct the Writer and see if write(d) creates the same file as the StringBuilder.

I had success looping through my 5 database rows and writing a CSV file, except the code that I used rewrote the file every line. I will use the CSVParser to read the file to import an activity from another computer. The examples I found online for append are few.

Can I start the Writer with append as true, or is there a better way to write the file. I used the following to write the CSV line from the String d built from the row of the database:

                try (Writer w = new OutputStreamWriter(fs.openOutputStream(String.valueOf(sendFile)))) {
                    w.write(d);
                } catch (Exception e) {
                    Log.p("Error " + e);
                }

Thanks.

Edit 1: This is the method I use to read the database into strings. Both Writer, as Shai showed me before (shown above), and writeToSting illustrated below (with \n added to the string) overwrite row 1 with row 2, etc. and at conclusion give a csv file with only row 5.

    public void toSVC(addActivity c) throws IOException, InstantiationException {
        namet = c.name.toString();
        dbsa = Display.getInstance().openOrCreate("pandr.db");
        String rd = "SELECT * FROM pandr WHERE name ='" + namet + "'";
        cursa = dbsa.executeQuery(rd);
        Row currentRow = cursa.getRow();
        cc = currentRow.getInteger(3);
        x = cc + 1;
        rn = 1;
        for (r = 1; r < x; r++) {
            trecno = rn.toString();
            tname = currentRow.getString(1);
            tpos = currentRow.getInteger(2);
            posv = tpos.toString();
            ttr = currentRow.getInteger(3);
            trv = ttr.toString();
            tbloc = currentRow.getString(4);
            tlwloc = currentRow.getString(5);
            tcfloc = currentRow.getString(6);
            trwloc = currentRow.getString(7);
            tamloc = currentRow.getString(8);
            tcmloc = currentRow.getString(9);
            tdmloc = currentRow.getString(10);
            tlcbloc = currentRow.getString(11);
            trcbloc = currentRow.getString(12);
            tlfbloc = currentRow.getString(13);
            trfbloc = currentRow.getString(14);
            tgloc = currentRow.getString(15);
            String d = trecno + "," + tname + "," + posv + "," + trv + "," + tbloc + "," + tlwloc + "," + tcfloc + "," + trwloc + "," + tamloc + "," + tcmloc + "," + tdmloc + "," + tlcbloc + "," + trcbloc + "," + tlfbloc + "," + trfbloc + "," + tgloc+"\n";
            String flname = new String("/" + namet + ".csv");
            FileSystemStorage fs = FileSystemStorage.getInstance();
            File sendFile = new File(fs.getAppHomePath() + flname);
            Util.writeStringToFile(sendFile, d);
            rn++;
        }
        dbsa.close();
        cursa.close();
        Util.cleanup(os);
        new FinishBanner();
    }
}

I first moved the Writer builder outside the loop, and tried w.write(d) for each row, but that gave me a java.lang.NullPointerException on row 2.

I also tried to use StringBuilder and sb.append(d) (with \n included at the end of the string) to the StringBuilder for the 5 rows, but sb.append(d) also gave me a java.lang.NullPointerException when trying to write the first line to the StringBuilder.

I thought the easiest way to accomplish this was create the file and append each row to the file, which is why I thought StringBuilder.append() would work. I am finding there aren't any website documents showing a way to accomplish this.

My goal is still to write a file that I can email and parse, and write into the activity database on a different device.

Edit 2 In my work to get the data order correct, I left off cursa.next(), which was why I got line 1 repeated. If I went back to my original code, Writer would work.

A new problem has manifest with this method. The StringBuilder sb has the first line twice. I increased x to 7, and the StringBuilder showed line 5 from the database as line 6 in sb.

Here is the current loop with the same head as above:

        for (r = 1; r < x; r++) {
            trecno = rn.toString();
            tname = currentRow.getString(1);
            tpos = currentRow.getInteger(2);
            posv = tpos.toString();
            ttr = currentRow.getInteger(3);
            trv = ttr.toString();
            tbloc = currentRow.getString(4);
            tlwloc = currentRow.getString(5);
            tcfloc = currentRow.getString(6);
            trwloc = currentRow.getString(7);
            tamloc = currentRow.getString(8);
            tcmloc = currentRow.getString(9);
            tdmloc = currentRow.getString(10);
            tlcbloc = currentRow.getString(11);
            trcbloc = currentRow.getString(12);
            tlfbloc = currentRow.getString(13);
            trfbloc = currentRow.getString(14);
            tgloc = currentRow.getString(15);
            sb.append(trecno).append(",")
                        .append(tname).append(",")
                        .append(posv).append(",")
                        .append(trv).append(",")
                        .append(tbloc).append(",")
                        .append(tlwloc).append(",")
                        .append(tcfloc).append(",")
                        .append(trwloc).append(",")
                        .append(tamloc).append(",")
                        .append(tcmloc).append(",")
                        .append(tdmloc).append(",")
                        .append(tlcbloc).append(",")
                        .append(trcbloc).append(",")
                        .append(tlfbloc).append(",")
                        .append(trfbloc).append(",")
                        .append(tgloc).append(",")
                        .append("\n");
            rn++;
            cursa.next();
        }

I am going to reconstruct the Writer and see if write(d) creates the same file as the StringBuilder.

Share Improve this question edited Mar 25 at 2:27 curtjacobs1 asked Mar 19 at 4:07 curtjacobs1curtjacobs1 3791 silver badge8 bronze badges 8
  • 1 In order to break the lines you need to have \n entries to mark the line breaks. The content of d is where those line breaks should appear. How do you generate that variable? – Shai Almog Commented Mar 20 at 2:16
  • I am taking the Interger toString for 2 of the 16 columns in the database and the text for the other 14, and adding a comma between them to define d. I loop through the 5 rows, and the class created a new file for each line. When I read the csv file, it opened in Numbers, and the information was the data from the 5th row of the play from the database. My issue, then is how to print each of the lines from the database. Some of the "activities" could have more lines in the database, and each line uses the same variables (columns). – curtjacobs1 Commented Mar 21 at 3:17
  • Can you edit the question to include the code instead of describing it? It's hard to follow that description. You need to use \n when building a CSV. – Shai Almog Commented Mar 21 at 4:32
  • Thanks, Shai. I got StringBuilder to record all 5 rows earlier, but the values were the same for all 5 lines in the CSV. I tried to find a way to iterate d to accept the next row's data, but that did not work. I just built the row using the csvString.append code you wrote in the answer, but csvString still carried the data from line 1 into all 5 rows of the file written. It acts like the values in the next row will not overwrite the values stored in csvString after the first pass through the loop. – curtjacobs1 Commented Mar 24 at 3:15
  • You just need to move the file opening and closing out of the loop. At present you're creating a new file per line. – user207421 Commented Mar 24 at 4:54
 |  Show 3 more comments

1 Answer 1

Reset to default -1

The best way to do this would be with a StringBuilder then write that to the writer. E.g.

        StringBuilder csvString = new StringBuilder();
        for (r = 1; r < x; r++) {
            trecno = rn.toString();
            tname = currentRow.getString(1);
            // etc...
            csvString.append(trecno).append(",")
                     .append(tname).append(",")
                     // etc. for other entries
                     .append("\n");
            rn++;
        }
        String flname = new String("/" + namet + ".csv");
        FileSystemStorage fs = FileSystemStorage.getInstance();
        File sendFile = new File(fs.getAppHomePath() + flname);
        Util.writeStringToFile(sendFile, csvString.toString());
发布评论

评论列表(0)

  1. 暂无评论