Results 1 to 3 of 3
  1. #1
    jessie is offline Member
    Join Date
    Nov 2010
    Posts
    29
    Rep Power
    0

    Default Writing a long string to a text file

    Hi,

    im writing a huge string into a text file in my java program...the full text is getting printed in the system.out.println() statement.... but full text is not getting printed in the text file...only the last line is getting printed...can sumbdy tell me why is this and can you give me a solution? this is my code snippet..

    List<ArrayList<? extends HasWord>> sentences = tagger.tokenizeText(new BufferedReader(new FileReader("D:/out.txt")));
    for (ArrayList<? extends HasWord> sentence : sentences) {
    ArrayList<TaggedWord> tSentence = tagger.tagSentence(sentence);
    String outnew = Sentence.listToString(tSentence, false);


    System.out.println(outnew);

    try{
    // Create file
    FileWriter fstream = new FileWriter("D:/outnew.txt");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write(outnew);
    //Close the output stream
    out.flush();
    out.close();
    }catch (Exception e){//Catch exception if any
    System.err.println("Error: " + e.getMessage());
    }


    jessie..

  2. #2
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    You're recreating the file every time you go to write to the file. Create the file before the for loop, and close the streams/writers after it ends. You should probably only flush the writer after the loop as well.

    In pseudocode:

    Java Code:
    set up strings to write;
    create FileWriter and BufferedWriter;
    
    for(sentence in senctences){
         create string to be written;
         try{
              write string to file;
         }catch(IOException){
              print error message;
         }
    }
    close writers;
    Also, when posting code, please place code tags ([code] and [/code]) around the code. The code then retains its formatting, as with the pseudocode above, making it easier to read.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  3. #3
    jessie is offline Member
    Join Date
    Nov 2010
    Posts
    29
    Rep Power
    0

Similar Threads

  1. Writing a long string to a text file
    By jessie in forum New To Java
    Replies: 2
    Last Post: 11-06-2010, 04:44 PM
  2. Replies: 4
    Last Post: 10-10-2010, 10:57 AM
  3. Replies: 1
    Last Post: 02-27-2010, 01:29 AM
  4. writing to text file problem
    By blumdiggity in forum Networking
    Replies: 1
    Last Post: 02-26-2010, 02:43 PM
  5. writing text to file
    By notwist in forum New To Java
    Replies: 3
    Last Post: 04-25-2008, 04:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •