Solved

Print to File New line space question...

Posted on 2004-09-16
25
205 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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
 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
egit plugin on eclipse 8 98
servlet example 17 59
Running JavaFX on JDeveloper 12C 1 76
Glassfish admin console not working 1 56
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

756 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