Solved

Print to File New line space question...

Posted on 2004-09-16
25
201 Views
Last Modified: 2010-03-31
Hi, I am trying to write text to a file.  Each time this method is called I want the new text to go on the bottom of older text.  I am using "\n" newline space to try to do this.   However, this does not seem to work when I open the txt document, because all text is next to each other.  However, if I open the text file using a text editor like EditPlus, the "\n" are respected.  Can you please look at code below and possible fix this?

If possible, please provide some code.

Thanks,
G



************************* code ***********************
import java.io.*;

public class filePractice{
   
    public static void printFile(String filePath, String fileName, String contents) throws Exception{
        BufferedReader br = null;
        String input = null;
        FileOutputStream fos = null;
        try{          
               
                fos = new FileOutputStream(filePath + fileName, true);
                fos.write(("\n" +contents+"\n").getBytes()); //Does not print new line spaces...
                fos.flush();
                //fos.close();
           
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if (br != null){
                br.close();
            }
            if (fos != null){
            fos.close();
            }
        }
    }

public static void main(String args[]) throws Exception{
        printFile("c:/temp/","test_09_16", "*** Testing 228");
    }


}
0
Comment
Question by:gen228
  • 13
  • 11
25 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12078610
Try

PrintWriter out = new PrintWriter(new FileWriter(new File(filePath, fileName), true));
out.println(content);
0
 

Author Comment

by:gen228
ID: 12078701
Hi CEHJ, thanks for your comment, I am getting this compilation error:

symbol  : constructor FileWriter  (java.io.File,boolean)
location: class java.io.FileWriter
                PrintWriter out = new PrintWriter(new FileWriter(new File(filePath, fileName), true));

Thanks,
G.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12078756
You must be using an old version of Java. Do it like this then

File f = new File(filePath, fileName);
PrintWriter out = new PrintWriter(new FileWriter(f.getName(), true));
0
 

Author Comment

by:gen228
ID: 12078843
Thanks CEHJ for you comment, but in notepad it is still doiing the same thing, it is not respecting the new line...  Does it work on your notepad?

Thanks,
G
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12078866
If you want to start on a completely new line, you can do

out.println();
out.println(contents);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12078870
That should work - even in notepad ;-)
0
 

Author Comment

by:gen228
ID: 12078893
Thanks again CEHJ, I tried that but it still doesn't seem to work, I always get a box that I guess stands for the newline, is this only a Notepad thing, ?  because on more advanced editors like EditPlus, I don't get this problem.

Thanks,
G
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12078950
Yes, it is a Notepad thing, although i'm surprised it's happening. Try this

out.print("\r\n".getBytes());
out.print(contents);
out.print("\r\n".getBytes());
0
 

Author Comment

by:gen228
ID: 12079084
Thanks CEHJ, I really appreciate your effort.  Does this happen on your notepad also, could it be notepad does not understand the '\n' syntax?

Thanks,
G.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12079175
The point is that *literally* '\n' is the newline character. Notepad can't cope with anything other than windows line feeds ("\r\n"). But the odd thing is that Java should convert '\n' to the correct platform linefeed automatically. I take it that my last code corrected the problem?
0
 

Author Comment

by:gen228
ID: 12079210
Hi CEHJ, I am still getting the same results, below is exactly what I am running right now:

package java_IO_Practice;

import java.io.*;

public class Copy{

public static void printFile(String filePath, String fileName, String contents) throws Exception{
        BufferedReader br = null;
        String input = null;
        FileOutputStream fos = null;
        try{          
               
                fos = new FileOutputStream(filePath + fileName, true);
                fos.write(("\n" +contents+"\n").getBytes()); //Does not print new line spaces...

                //PrintWriter out = new PrintWriter(new FileWriter(new File(filePath, fileName), true));
                //out.println(content);
                File f = new File(filePath, fileName);
                PrintWriter out = new PrintWriter(new FileWriter(f.getName(), true));
                out.print("\r\n".getBytes());
                out.print(contents);
                out.print("\r\n".getBytes());          

                fos.flush();
                //fos.close();
           
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            if (br != null){
                br.close();
            }
            if (fos != null){
            fos.close();
            }
        }
    }

public static void main(String args[]) throws Exception{
        printFile("c:/temp/","text_test.txt", "*** Testing 228");
    }


}
0
 

Author Comment

by:gen228
ID: 12079274
My apologies, CEHJ, the program has other lines that I didn't delete yet...I am looking at it right now.

G.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 86

Accepted Solution

by:
CEHJ earned 68 total points
ID: 12079325
This works fine for me in Notepad:


import java.io.*;

public class Copy {

      public static void printFile(String filePath, String fileName, String contents) throws Exception{
            File f = new File(filePath, fileName);
            PrintWriter out = new PrintWriter(new FileWriter(f.getName(), true));
            out.println(contents);
            out.close();
      }

      public static void main(String args[]) throws Exception{
            printFile(".","test.txt", "*** Testing 228");
      }


}
0
 

Author Comment

by:gen228
ID: 12079449
Hi CEHJ !, your solution is excellent, it works great!  My only last question is I am doing:

public static void main(String args[]) throws Exception{
          printFile("c:/temp/","cab.txt", "*** Testing 228");
}

However, the "cab.txt" file is not going to c:/temp directory, instead it is going to the same directory as my Copy java class.  Is the filePath being ignored?

-G
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12079553
C:\temp should already exist if you want to do that
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 12081669
And these solutions work for JAVA 2 1.3

The earliest solution CEHJ gave is good for JAVA 2 1.4 and later (appending to a file).

;JOOP!
0
 

Author Comment

by:gen228
ID: 12084200
Thank you sciuriware for your comment

G.
0
 

Author Comment

by:gen228
ID: 12084210
Thanks CEHJ for all your comments and code.  I have c:/temp existing, but it still seems to want to go to only the immediate directory(directory of my java class and source).  Anyway, if you have any comments about this, please post !  Thanks again for your great answers !

Thanks again,
G.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12084307
>>but it still seems to want to go to only the immediate directory(directory of my java class and source).  

Any difference if you do

PrintWriter out = new PrintWriter(new FileWriter(f.getName(), true));

?
0
 

Author Comment

by:gen228
ID: 12084666
Hi CEHJ, thank you for your continued help.... I have tried the above code and it still doesn't seem to take in the directory path...here is my code... I am using jdk 1.3.1   Thanks -G

import java.io.*;

public class Copy{

     public static void printFile(String filePath, String fileName, String contents) throws Exception{
          File f = new File(filePath, fileName);
         
          PrintWriter out = new PrintWriter(new FileWriter(f.getName(), true));


          out.println(f.getPath());
          out.println(contents);
          out.close();
     }

     public static void main(String args[]) throws Exception{
          printFile("c:/tempLogin/","login.txt", "*** NUMBER ONE ***");
     }


}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12084725
LOL sorry. I meant to say

PrintWriter out = new PrintWriter(new FileWriter(f.getPath(), true));
0
 

Author Comment

by:gen228
ID: 12084817
LOL, oh my goodness, I didn't notice that either!  It works now!  Thanks, CEHJ for you great answers !  And thanks for continuing to help !  

Thanks again,
G.
0
 

Author Comment

by:gen228
ID: 12084831
BTW, if I open a new question in the future, is there any way to notify you? can I comment on this question link and you will get a notification?

Thanks,
G.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12085381
:-)

>>BTW, if I open a new question in the future, is there any way to notify you?

I'm almost certainly going to be among the first to see it anyway ;-)
0
 

Author Comment

by:gen228
ID: 12085518
Thank you
-G
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now