BufferedWriter

I'm writing to a file and I'm having a problem organizing the data when the write happens. As it happens now, I have a string array called source[]. when a submit button is pressed, a method pulls data from several textfields and stores them into source[]. it then writes the array to the .txt file. The problem is that everything gets written in one big sentance, with no breaks, spaces or new lines. I would be happy just to get it to print the data on a seperate line for each index in the array. How do I do this? Here is the code I use to write to the file, with "source" being a string array the size of my textFields.length:
try
source = getFields();
setFields();
for(int counter = 0; counter < labels.length; counter++)
source[counter].trim();
BufferedWriter bw = new BufferedWriter(new FileWriter("Form.txt", true));
for(int counter = 0; counter < labelNames.length; counter++)
bw.write(source[counter]);
bw.flush();
bw.close();
catch (Exception e)
System.err.println("Error writing to file");
}

hi,
do this:for(int counter = 0; counter < labelNames.length; counter++)
    bw.write(source[counter]);
    bw.write ("\n");
}greetings,
Stijn

Similar Messages

  • Taking too much time using BufferedWriter to write to a file

    Hi,
    I'm using the method extractItems() which is given below to write data to a file. This method is taking too much time to execute when the number of records in the enumeration is 10000 and above. To be precise it takes around 70 minutes. The writing pauses intermittently for 20 seconds after writing a few lines and sometimes for much more. Has somebody faced this problem before and if so what could be the problem. This is a very high priority work and it would be really helpful if someone could give me some info on this.
    Thanks in advance.
    public String extractItems() throws InternalServerException{
    try{
                   String extractFileName = getExtractFileName();
                   FileWriter fileWriter = new FileWriter(extractFileName);
                   BufferedWriter bufferWrt = new BufferedWriter(fileWriter);
                   CXBusinessClassIfc editClass = new ExploreClassImpl(className, mdlMgr );
    System.out.println("Before -1");
                   CXPropertyInfoIfc[] propInfo = editClass.getClassPropertyInfo(configName);
    System.out.println("After -1");
              PrintWriter out = new PrintWriter(bufferWrt);
    System.out.println("Before -2");
              TemplateHeaderInfo.printHeaderInfo(propInfo, out, mdlMgr);
    System.out.println("After -2");
    XDItemSet itemSet = getItemsForObjectIds(catalogEditDO.getSelectedItems());
    Enumeration allitems = itemSet.allItems();
    System.out.println("the batch size : " +itemSet.getBatchSize());
    XDForm frm = itemSet.getXDForm();
    XDFormProperty[] props = frm.getXDFormProperties();
    System.out.println("Before -3");
    bufferWrt.newLine();
    long startTime ,startTime1 ,startTime2 ,startTime3;
    startTime = System.currentTimeMillis();
    System.out.println("time here is--before-while : " +startTime);
    while(allitems.hasMoreElements()){
    String aRow = "";
    XDItem item = (XDItem)allitems.nextElement();
    for(int i =0 ; i < props.length; i++){
         String value = item.getStringValue(props);
         if(value == null || value.equalsIgnoreCase("null"))
              value = "";
                             if(i == 0)
                                  aRow = value;
                             else
                                  aRow += ("\t" + value);
    startTime1 = System.currentTimeMillis();
    System.out.println("time here is--before-writing to buffer --new: " +startTime1);
    bufferWrt.write(aRow.toCharArray());
    bufferWrt.flush();//added by rosmon to check extra time taken for extraction//
    bufferWrt.newLine();
    startTime2 = System.currentTimeMillis();
    System.out.println("time here is--after-writing to buffer : " +startTime2);
    startTime3 = System.currentTimeMillis();
    System.out.println("time here is--after-while : " +startTime3);
                   out.close();//added by rosmon to check extra time taken for extraction//
    bufferWrt.close();
    fileWriter.close();
    System.out.println("After -3");
    return extractFileName;
    catch(Exception e){
                   e.printStackTrace();
    throw new InternalServerException(e.getMessage());

    Hi fiontan,
    Thanks a lot for the response!!!
    Yeah!! I kow it's a lotta code, but i thought it'd be more informative if the whole function was quoted.
    I'm in fact using the PrintWriter to wrap the BufferedWriter but am not using the print() method.
    Does it save any time by using the print() method??
    The place where the delay is occurring is the wile loop shown below:
                while(allitems.hasMoreElements()){
                String aRow = "";
                    XDItem item = (XDItem)allitems.nextElement();
                    for(int i =0 ; i < props.length; i++){
                         String value = item.getStringValue(props);
         if(value == null || value.equalsIgnoreCase("null"))
              value = "";
                             if(i == 0)
                                  aRow = value;
                             else
                                  aRow += ("\t" + value);
    startTime1 = System.currentTimeMillis();
    System.out.println("time here is--before-writing to buffer --out.flush() done: " +startTime1);
    bufferWrt.write(aRow.toCharArray());
    out.flush();//added by rosmon to check extra time taken for extraction//
    bufferWrt.flush();//added by rosmon to check extra time taken for extraction//
    bufferWrt.newLine();
    startTime2 = System.currentTimeMillis();
    System.out.println("time here is--after-writing to buffer : " +startTime2);
    What exactly happens is that after a few loops it just seems to sleep for around 20 seconds and then again starts off and ............it goes on till the records are done.
    Please do lemme know if you have any idea as to why this is happening !!!!! This bug is giving me the scare.
    thanks in advance

  • How to write Strings in a text file with BufferedWriter

    I've got a Vector object full of Strings objects, I'm interested in wrinting these Strings in a text file with a BufferedWriter , I would apreciate some code, thank you

    http://java.sun.com/products/jdk/1.2/docs/api/java/io/BufferedWriter.html
    "PrintWriter out = new PrintWriter(new BufferedWriter((new FileWriter("foo.out")));"

  • Can't a BufferedReader and a BufferedWriter be open at the same time?

    To the experienced:
    I am writing a class to selectively extract data from an Excel file, and write out to a plain text file. I am using JDeveloper 11.1.1.3.
    It works fine and writes out the output file as expected when reading data from the spreadsheet and directly writing to the output file.
    However, I need to convert the data in one of the columns based on a conversion table. The conversion table is a plain text file that has two columns separated by a space. I read in the conversion table using a BufferedReader and put it in a HashMap for use. However, once the Buffered Reader and the HashMap are introduced, the BufferedWriter does not work any more.
    The way the class works is that, the main() method (not shown here) reads data from the Excel sheet into a List, and then calls the method showExcelData() (as shown below) to write out data from the List to a plain text file.
    When the green color code was not added, the output file was written to the disk fine. A sample line from the output file is:
    JOHN:DOE:11223344:12345:20110824By adding the green code, I expect it to output the line as:
    JOHN:DOE:11223344:STUDENT:20110824The problem is, after the green code is added, the output file the program writes to the disk is zero size.
    I added the System.out.println() lines for troubleshooting. These lines show that the BufferedWriter <b>out</b> is not null, and the conversion is actually taking place. But <b>out.write()</b> simply does not work. Commenting out the green code, the program is working again - of course, without date conversion for that column.
    There must be something wrong but I can not see where it is wrong.
    Your help is very much appreciated!
    Newman
    <pre>
    private static void showExcelData(List sheetData, String outputFilename) throws IOException {
    BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename));
    System.out.println("Is out null? " + (out == null));
    BufferedReader in = null;
    for (int i = 3; i < sheetData.size(); i++) {
    List list = (List)sheetData.get(i);
    for (int j = 0; j < list.size(); j++) {
    HSSFCell cell = (HSSFCell)list.get(j);
    if (j == 5 || j == 6 || j == 7 || j == 11) {
    <font color="green"><b>
    // The column with index 11 is the column of data that needs conversion:
    if (j == 11) {
    String convertionFilename = "ConversionTable.txt";
    Map<String, String> liveMap =
    new HashMap<String, String>();
    try {
    in = new BufferedReader(new FileReader(convertionFilename));
    String line = null;
    while ((line = in.readLine()) != null) {
    String[] keyValue = line.split(" ");
    liveMap.put(keyValue[0], keyValue[1]);
    } catch (IOException e) {
    String message = e.getMessage();
    String titleCode =
    cell.getRichStringCellValue().toString();
    String role = liveMap.get(titleCode).toUpperCase();
    out.write(role);
    System.out.println(titleCode + " " + role);
    } else {</b></font>
    out.write(cell.getRichStringCellValue().toString().toUpperCase());
    System.out.println(cell.getRichStringCellValue().toString().toUpperCase());<font color="green"><b>
    }</b></font>
    if (j < list.size() - 1 && j != 11) {
    out.write(":");
    } else if (j == 26) {
    if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
    if (DateUtil.isCellDateFormatted(cell)) {
    Calendar cellDate = Calendar.getInstance();
    cellDate.setTimeInMillis(cell.getDateCellValue().getTime());
    String year = "" + cellDate.get(Calendar.YEAR);
    String month =
    padding(cellDate.get(Calendar.MONTH) + 1);
    String day =
    padding(cellDate.get(Calendar.DAY_OF_MONTH));
    String expDate = year + month + day;
    out.write(":" + expDate);
    out.write(System.getProperty("line.separator"));
    if (in != null) in.close();
    if (out != null) out.close();
    </pre>

    Hi, All,
    This posting is at the bottom of the stack. Quite a few more postings were added on top of this and solved, and now I reach back to this one.
    The main problems are:
    1. Close the I/O buffer after finishing using it. Otherwise the data in the buffer do not get flushed to the file on the disk. I think that is the cause of the problem of getting zero sized output file.
    2. Do not count on Excel to stop at a blank cell by using Ctrl-down / Ctrl-up. The file I am processing is produced by some reporting program which, I think, instead of skipping the cell, puts a zero-sized string in it. Obviously, Excel does not stop at such cells. I had checked the columns using the Ctrl-down/Ctrl-up key and through that column did not have blank cells. Sharp-eyed gimbal2 spotted the problem, and led me to re-inspect the column by using up/down arrow keys instead, and found the blank cells. Such empty strings are used in my code as key in searching the map (String role = liveMap.get(titleCode).toUpperCase();) and caused the problem.
    And the lesson is, when doing some quick and dirty tests, do not get too quick and too dirty, which can end up slower rather than faster.
    Many thank to all of you for giving me the helping hand!
    Newman

  • Can't create a file by using BufferedWriter

    Hello,
    I am going to create a new html file "C:\test1.html" by modifying the old file "C:\test.html".
    However I have not seen the file in the c driver.
    Thanks for any help.
    import java.awt.Point;
    import java.io.*;
    import java.util.*;
    public class AddIdinHtml
         private File file1;
    //     private File file2;
    //     private HashMap<String, Double> sta;
         public void AddId() {
    //     public void AddIdinHtml(String FileName, String Directory) {
         String path = System.getProperty("user.dir");
          try{
    //      String filenames = path+'/'+Directory+'/'+FileName;
              String filenames = "C:\\test.html";
          FileInputStream fstream = new FileInputStream(filenames);
        // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String Line;
            String secondLine;
    //        firstLine = br.readLine();
            String[] parts;
            String[] newLines;
            int lineId = 0;
            List contents = new ArrayList();
            while ((Line = br.readLine()) != null)   {
                Line = Line.trim();
                contents.add(Line);
                if(Line.startsWith("<body")){
                    while ((Line.startsWith("</body")!= true)) {
                        Line = br.readLine();
    //                System.out.println(Line);
                    parts = Line.split("\\s");
                    if(Line.startsWith("<p")){
                       Line = "<p"+" "+"id="+lineId+Line.substring(2,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<li")){
                       Line = "<li"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<li")){
                       Line = "<li"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h1")){
                       Line = "<h1"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h2")){
                       Line = "<h2"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h3")){
                       Line = "<h3"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h4")){
                       Line = "<h4"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h5")){
                       Line = "<h5"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h6")){
                       Line = "<h6"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<div")){
                       Line = "<div"+" "+"id="+lineId+Line.substring(4,Line.length());
                       contents.add(Line);
                       System.out.println(Line);
                       lineId++;
                    else if (Line.startsWith("<table")){
                       Line = "<table"+" "+"id="+lineId+Line.substring(6,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<tr")){
                       Line = "<tr"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<th")){
                       Line = "<th"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<td")){
                       Line = "<td"+" "+"id="+lineId+Line.substring(4,Line.length());
                       contents.add(Line);
                       lineId++;
    //            contents.add(Line);
                lineId++;
             file1 = new File("C:\\test1.html");
                if(file1.exists())//to judge if difference file exists,delete it
                    file1.delete();
             FileWriter outFile1 = new FileWriter(file1,true);
                BufferedWriter out1 = new BufferedWriter(outFile1);
               newLines = (String[]) contents.toArray(new String[contents.size()]);
               StringBuffer buffer2 = new StringBuffer();
               for(String rec : newLines){
                     buffer2.append(rec);
                     buffer2.append("\n");
                     out1.write(buffer2.toString());
                     out1.flush();
              in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error1: " + e.getMessage());
        public static void main(String[] args){
            AddIdinHtml ad = new AddIdinHtml();
            ad.AddId();
    }

    kajbj,
    you are right. It is not executing.
    I added one printing but no output.for(String rec : newLines){
                      StringBuffer buffer2 = new StringBuffer();
                     buffer2.append(rec);
                       System.out.println("test");// no printing here
                     buffer2.append("\n");
                     out1.write(buffer2.toString());
                     out1.flush();
               }but why?

  • Need help about method close() in BufferedWriter Class

    Hi All,
    I'm a newbie in Java programming and I have problem regarding BufferedWriter class. I put the code snippet below.
    Sometimes I found wr.close() need a long time to be executed, around 9 seconds. For the normal case, it only needs 1 second. The transaction is same with the normal case and I found no errors in the log.
    Do you guys have any idea about this problem? What cases that can cause this problem?
    Thanks
    // Create a socket to the host
    InetAddress addr = InetAddress.getByName(shost);
    Socket socket = new Socket(shost, sport);
    // Send header
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    data = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><request><contentcode>" + content_code +"</contentcode><msisdn>"+ orig_num +"</msisdn></request>";
    System.out.println("------------POST----------");
    wr.write("POST /" + surlname +" HTTP/1.1\r\n");
    wr.write("Host: " + shost + "\r\n");
    wr.write("Connection: close \r\n");
    wr.write("Content-type: text/xml \r\n");
    wr.write("Content-length: " + data.length() + "\r\n");
    wr.write("\r\n");
    wr.write(data);
    System.out.println("POST /" + surlname +" HTTP/1.1\r\n");
    System.out.println("Host: " + shost);
    System.out.println("Connection: close");
    System.out.println("Content-type: text/xml");
    System.out.println("Content-length: " + data.length());
    System.out.println("-------------------------");
    System.out.println("data = " + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><request><contentcode>" + content_code +"</contentcode><msisdn>"+ orig_num +"</msisdn></request>");
    wr.flush();
    // Get response
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while ((linelength = rd.read(charline)) >0) {
    reply += new String(charline, 0, linelength);
    wr.close();
    rd.close();
    System.out.println("reply = " + reply);
    log.info("(New Log) reply = " + reply);

    sabre150 wrote:
    So what makes you think that not using StringBuffer is the cause of the OP's problem?Just by experience. The main cause of resource hogs in Java is large string concatenation enclosed in a loop.
    I've just made the following experience :
    public class Test {
        public static void main(String[] args) {
            new Test().execute();
        private void execute() {
            long a, b, c;
            String value = "A123456789B123456789C123456789D123456789";
            String reply = "";
            StringBuffer buffer = new StringBuffer();
            a = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) { reply += value; }
            b = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) { buffer.append(value); }
            reply = buffer.toString();
            c = System.currentTimeMillis();
            System.out.println("Duration - concatenation = " + (b-a) + " / string buffer = " + (c-b));
    }Output :
    Duration - concatenation = 21295 / string buffer = 7

  • Null Pointer Exception with BufferedWriter

    Hi Guys,
    When I try to run this code I get a NullPointer Exception, and I can't work out why. At first I thought it was to do with scope, as it looks like it can't find the out object, but after fiddling with the code it didn't make any difference.
    Could please have a look and let me know what you think?
    Thanks
    import java.io.*;
    public class Storage {
        protected File file;
        protected String path = "C:/Users/Chicky/Documents/NetBeansProjects/Drive/Input";
        protected String filepath = "C:/Users/Chicky/Documents/NetBeansProjects/Drive/Input/Data.csv";
        protected FileWriter fw;
        protected BufferedWriter out;
        public void Storage(){
        protected void setup() throws IOException{
            file = new File(path);
            if(!file.isDirectory()){
                file.mkdir();
                fw = new FileWriter(filepath, true);
            else if(file.isDirectory() && file.exists()){
                //don't want to do anything here
            out = new BufferedWriter(fw);    //<----------line 34
    import java.io.*;
    public class Main {
        public static Storage store;
        public static void main(String[] args)throws IOException {
            store = new Storage();
            store.setup();        //<--------------line 30
            start();
        ...Exception in thread "main" java.lang.NullPointerException
    at java.io.Writer.<init>(Writer.java:71)
    at java.io.BufferedWriter.<init>(BufferedWriter.java:83)
    at java.io.BufferedWriter.<init>(BufferedWriter.java:70)
    at drive.Storage.setup(Storage.java:34)
    at drive.Main.main(Main.java:30)

    Thanks to both camickr and pbrockway2, I've got it working. fw wasn't initialised if the directory already existed so this is my new code which works fine.
        protected void setup() throws IOException{
            file = new File(path);
            if(!file.isDirectory()){
                file.mkdir();
            else if(file.isDirectory() && file.exists()){
               //don't need to do anything here
            fw = new FileWriter(filepath, true);
            out = new BufferedWriter(fw);
        }

  • Need help about bufferedWriter

    i wrote code like below:
         try
         URL currentUrl= event.getURL();
         BufferedWriter out = new BufferedWriter(new FileWriter("his.txt"));
         out.write(currentUrl+"\n");
         out.close();
         catch (IOException e) {}
    for example, i browse "www.bbc.co.uk","www.manutd.com","www.hotmail.com"three web page
    I want to print all of them in his.txt
    but every time, it only got the last web address I browsed,
    can any one help me how 2 print all the addresses in the file?
    thanks a lot

    ... (new FileWriter("his.txt", true) ...
    To tell the FileWriter that you want to append stuff to it rather than rewrite it from scratch.

  • Question about BufferedWriter

    my program is underlying:
    import java.io.*
    BufferedWriter bw=new BufferedWriter(new FileWriter("output.txt"));
    long stTime = System.currentTimeMillis();
    long enTime = System.currentTimeMillis();
    long durTime=enTime-stTime;
    bw.write(durTime);
    bw.newLine();
    bw.close();
    Why everytime I compile the java file, it returns "cannot reslove symbol" in
    bw.write();
    ^^
    bw.newLine();
    ^^
    bw.close();
    ^^

    I've tried putting BufferedWriter in try-block and
    following test:
    import java.io.*
    main{
    try{
    FileWriter fw= new FileWriter("output.txt");
    BufferedWriter bw=new BufferedWriter(fw);
    }catch (IOException e){
    bw.write("test");
    bw.newLine();
    bw.close();
    still return the same error meg...
    cannot resolve symbol : bw for these three comments.Enclose your bw operations within the same block.
    try{
    FileWriter fw= new FileWriter("output.txt");
    BufferedWriter bw=new BufferedWriter(fw);
    bw.write("test");
    bw.newLine();
    bw.close();
    }catch (IOException e){
    ...}The problem is that the symbol bw is only defined within the scope of the try/catch block. You might declare it outside of the block like this:
    BufferedWriter bw = null;
    try {
    catch (IOException ex) {...}but if you want to use your BufferedWriter after the try/catch block you'll have to check if it ain't null.
    And (of course) use the appropriate data format with your method calls :-)

  • Appending, overwriting to a file, using BufferedWriter

    I have modify a file using BufferedWriter, plz suggest

    To append to a file with a BufferedWriter, use getBuffWriterForAppend(String filename)
        FileWriter fw = new FileWriter(filename, true);
        return new BufferedWriter(fw);
    } If you want to overwrite some of the contents, I think you need a RandomAccessFile. This doesn't appear to be usable with a BufferedWriter (unless you want to create a big wrapper - the BufferedWriter wrapping an OutputStreamWriter wrapping a PipedOutputStream which is connected to a PipedInputStream which has another thread reading from it and copying to the RandomAccessFile).
    Answer provided by Friends of the Water Cooler. Please inform forum admin via the
    'Discuss the JDC Web Site' forum that off-topic threads should be supported.

  • Simple BufferedWriter/FileWriter error

    This code is driving me nuts. I can read files without a problem, but I can't seem to write anything for the life of me. I've tested the ArrayList passed to the constructor and it works fine. For my sake, assume that's not the problem. The global variables save and admin are accessed through other classes, they're meant to be public. Can anyone please proofread the code and see where I screwed up? :(
    import java.io.*;
    import java.util.*;
    public class LifeDataThread extends Thread {
         private ArrayList<LifePlayer> players;
         private String fileName;
         public boolean save = true;
         public boolean admin = false;
         private final String file = "data.bak";
        public LifeDataThread(ArrayList<LifePlayer> list, String fn) {
             players = list;
             fileName = fn;
        @Override
        public void run() {
             try {
                  while (save) {
                       if (admin == true) save = false;
                       else Thread.sleep(1000*60*5);
                       System.out.println("SAVING DATA.");
                       BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                       BufferedReader br = new BufferedReader(new FileReader(file));
                       bw.write("" + players.size() + 1);
                      for (int x = 0; x < players.size(); x++) {
                           LifePlayer temp = players.get(x);
                           bw.write(temp.toString());
                           System.out.println(br.readLine());
                      File f = new File(fileName);
                      System.out.println("Delete " + fileName + ": " + f.delete());
                      f = new File(file);
                      System.out.println("Create " + file + ": done");
                      System.out.println("Rename " + file + " to " + fileName + ": " + f.renameTo(new File(fileName)));
                      bw.close();
                      br.close();
             catch (IOException e) {
                  e.printStackTrace();
             catch (InterruptedException e) {
                  System.err.println(e);
        }output:
    SAVING DATA.
    null
    null //4 players
    null
    null
    Delete data.dat: true
    Create data.bak: done
    Rename data.bak to data.dat: done

    This is pretty bizarre. You're trying to read a line from a file when you never write lines to the file, and you also seem to be expecting a write to show up immediately as something that can be read, which doesn't take any account of the various buffers you have installed in teh writing chain.
    If you want to test whether the file has been written, test its size after you've closed it. Or read it after you've stopped writing it and have closed the output writer.

  • BufferedWriter try catch Scoping problem

    I developed a quick and dirty application to search through a file system for files that contain certain patterns in their names, and it works fine. My problem is I want to use a BufferedWriter to write the results out to a new text file, and a buffered writer must be enclosed in a try catch statement because of a possible IOException. Now the writer is out of scope of the method that needs to call it, and if I put it in the method a new writer and hence a new file will be created each time through. I am sure this is just a design flaw on my part but I have hit this problem before, I was wondering what is a way around this, so the writer can be instantiated, the method that will do that actual writing to the file will be called until the iteration is done, and then the program will exit.
    Here is my code, there are some unused variables and objects in there, namely I am not using the BufferedWriter at the moment and was just cutting and pasting from the console:
    Thanks!
    import java.io.*;
    import java.util.*;
    public class NextAttempt {
         static List<File> filelist = new ArrayList<File>();
         static PrintStream out = new PrintStream(System.out);
         static File f;
         public static void getWriter() {
              try {
                   BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\FILE.txt"));
                        for(File f: filelist)
                             writer.append(f.getAbsolutePath());
              catch (Exception e) {}
         public static List<File> browse(File BASE) {
              File[] temp=BASE.listFiles();
                   for (int i=0;i<temp.length;i++) {
                        if(temp.getAbsolutePath().contains(File.separator+"PATTERN")&&temp[i].getName().contains(".ext") {     
                             out.println(temp[i].getAbsolutePath());
                             //filelist.add(temp[i]);
                        else if (temp[i].isDirectory()) {
                                  BASE=temp[i];
                                  rec(BASE);
                        else {
                             BASE=new File("PATH");
              return filelist;
         public static void rec(File BASE) {
              browse(BASE);
         public static void main(String[] args) {
              browse(new File("PATH"));
              out.println("Complete");

    Also you can keep passing the file lists up to the callers, so the initial invocation of browse() will return a list of all the files. When you recurse (which you're doing now, apparently), you can append the return value of the recursive call to the caller's own list of files.
    Then just print the whole list when you're done.
    Another thing you might want to think about... you could use the logging framework to list the files as log entries. That may or may not be useful. The advantage is that the logging code already deals with some of these issues; the disadvantage is that producing a formatted log might result in a format you can't use, or tweaking the format might be more trouble than doing something else.

  • Definition of BufferedReader and bufferedwriter

    Can anyone give me better/more detail explanation or definition of bufferedreader and bufferedwriter?
    what is the difference of static and non-static variables?
    Thanks,
    heJuKp

    Ok, I didn't ask for a link in my message. I have already looked for what I want to know in the java.sun.com and other a few webpages already. I have been to the page that u provided in your message too. I have been through those tutorials many times. Those definitions are not very helpful to me. Reader reads, and writer writes. Of coz I know that. I know how to use those BufferedWriter and BufferedReader as much as I should. But I just want to know the better summerized definitions of them.
    For example - after reading all the notes from webpages, I have a summerized definition of "constructors"... Constructors have the same name with the class name. Constructor is a special method which is called when an object is created but before the object is used. Not having the return type, not even "void", is the major difference between constructors and othedr methods. Constructor is used for initializing the objects or instance variables. Constructors are invoked using the keyword "new". When the constructor is executed, all the variables and the objects are in fully useable state.
    I am asking for something like that for BufferedWriter and BufferedReader. Not a link. Just tell me what you know if you know.
    Thank you.
    Differences like that do not concern BufferedReader or
    BufferedWriter only. You're talking about Java
    language issues here.
    It's a good idea to plough your way through the Java
    Tutorials
    (http://java.sun.com/docs/books/tutorial/index.html)
    or get a good book on Java.
    To answer your question as well: static variables are
    class variables, while non-static variables belong to
    instances.

  • Conflict with FileWriter and bufferedWriter

    Hello all, i'm having problems with this code. The compiler says: The method put(String, BufferedWriter) in type Map<String, BufferedWriter> is not applicable for the arguments(String, FileWriter).
    Also there is another error that says: Cannot Cast From BufferedWriter to FileWriter.
    i understand that to use a BufferedWriter, you need a FileWriter, i'm not used to deal with maps and bufferedWriters together :/
    Thanks in advance!
    package pkg.mig;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    public class Uf_file {
         static Map<String, BufferedWriter> filemap;
         static Map<String, Long> filelenghmap;
         static Map<String, Integer> filesecuence;
         static FileWriter out;
            static BufferedWriter bw;
         public static void writeUF(String ufName, String sys, String uf_row) {
              if (filemap == null) {
                   filemap = new HashMap<String, BufferedWriter>();
                   if (filelenghmap == null) {
                        filelenghmap = new HashMap<String, Long>();
                        filesecuence = new HashMap<String, Integer>();
              if (filelenghmap.get(ufName) == null) {
                   filelenghmap.put(ufName, new Long(0));
                   filesecuence.put(ufName, new Integer(0));
              if (filemap.get(ufName) == null) {
                   try {
                        filemap.put(ufName, new FileWriter(getFileName(ufName, sys), true));
                        Utils.logger.info("Creando nuevo archivo: " + ufName +"-"+filesecuence.get(ufName));
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Utils.logger.severe(e.toString());
                        Utils.close_app(1);
              out = (FileWriter) filemap.get(ufName);
              try {
                   bw.write(uf_row);
                   filelenghmap.put(ufName, filelenghmap.get(ufName) + uf_row.length());
                   if (filelenghmap.get(ufName) > Long.parseLong(Utils.app_properties.getProperty("UF_Size"))) {
                        closeUF(ufName);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         static String getFileName(String ufName, String sys) {
              filesecuence.put(ufName, filesecuence.get(ufName) + 1);
              return sys + "." + ufName + "." + Utils.getDateSystem()+"EXT-"+Utils.app_properties.getProperty("EXT") +"-"+
              Utils.fNumber(Integer.toString(filesecuence.get(ufName)),3) + ".inp";
         static void closeUF(String ufName) {
              bw = (BufferedWriter) filemap.get(ufName);
              try {
                   out.close();
                   filemap.remove(ufName);
                   filelenghmap.put(ufName, (long) 0);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    }

    It has nothing to do with the map, you cannot cast from a file writer to a buffered writer, so here when you do this...
    static void closeUF(String ufName) {
              //bw = (BufferedWriter) filemap.get(ufName); // no
                                    bw = new BufferedWriter(filemap.get(ufName)); // yes
              try {
                   out.close();
                   filemap.remove(ufName);
                   filelenghmap.put(ufName, (long) 0);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         }Hope that helps!

  • BufferedWriter cannot append to file ....just overwrites

    Hello all,
    I have a java file that is an somewhat of a Event Handler.
    I have a method inside that is called many times while program runs.  public void writeToFile(String string)
          try
                BufferedWriter writer = new BufferedWriter(new FileWriter("foo.txt"));
                writer.append(string);
               // writer.write(string); tried this also.
                writer.flush();
                writer.close();
          catch(IOException io)
                    io.printStackTrace();
      }Problem is that I only get one line written to foo.txt, and each time I run the program it overwrites that one line with another value.
    Expected results are at least 4 lines would be written in foo.txt each time I run program.
    Any ideas?
    TIA!

    I dont suppose that you know if it is possible to
    append to the top (beginning)of the file?That would be inserting. To do that, you could store the whole file, then rewrite the file, putting the old data after your new data.
    Or you could create a new file, write the new data to it, then read the old file and write the data there to the new file. After that, delete the old file and rename the new file.

Maybe you are looking for

  • Linking to a MS word file in Safari does not open the file

    I access a web site that has hyperlinks to MS Word files. When I click on the link the following happens. 1. I get a new empty window 2. I get the download window showing the file But the file does not load in Word. I have to manually click on the fi

  • Re: Subscription expired message??

    I had quite some credit on Skype, suddenly I could not comunicate with contact partners. Received a message that my contract had expired. My credit is locked up, unless I pay an extra fee for some contract not specified, I will loose my credit if I d

  • Preview PDF Help

    Hello, Using Preview to view PDF...  It use to be able to view without downloading the file (ALT/Option Key and Link)...  Get Info is set to PREVIEW... Apply to ALL...  OSX Version 10.5.8... Please Help....  Getting Annoying....

  • Making Canada specifi changes to RPIPSR00 Payscale Reclassification Report

    Hi Guru's, We got the requirement to work around the standard SAP report Payscale Reclassification which RPIPSR00. Since this is not suits to our client specific Canada changes we are required to create a custom program or need to impliment BADI. Ple

  • Acrobat XI won't auto feed from scanner. Help

    I recently installed acrobat xi pro and when I try to scan from my computer to create a pdf, it is making me create a pdf one page at a time, instead of the entire document. Is this an Windows 8.1 issue? Is there help for this? JK in Houston