aspose file tools*
The moose likes I/O and Streams and the fly likes Writing data into file from a String variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Writing data into file from a String variable" Watch "Writing data into file from a String variable" New topic
Author

Writing data into file from a String variable

omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Hi friends,

In a program that i was trying, i have a string variable, which will hold the data that needs to be saved into a file. Now, the variable can contain any amount of text, with many whitespaces, new lines, OR special characters(as shown by notepad for binary data...for example the characters we see when we open image file in notepad) etc.,. I want to write all this data from the String variable into a file. I am not getting the starting point as to how i should start writing data into the file ?

Please help!

Thanks and Regards


Thanks and Regards
Omkar Patkar (SCJP 1.4)[url]http://javacollectionsnotes.blogspot.com[/url] | [url]http://omkar-myscjpexp.blogspot.com[/url]
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 686
Not sure I fully understand the data you are trying to write and how you want it to appear in the output file.
Could you give an example of the what would be in the String and how that would look in the file?
Strings normally hold data that is humanly readable, not the contents of a binary file like an image file.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8908
    
    8

A good place to start is the Java Tutorial chapter on IO


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Thanks Joe and Norm, but meanwhile, here is short example of what i want to achieve


Now, the value, present in the string is as it is...including \r \n \s etc., ... i mean i have this kind of data stored in a string variable after obtaining from another source. Now, i want to write this entire data ...right from Weblink\n695...upto -817C as it is in a File. So how do i do this ?

Thanks and Regards
Omkar Patkar
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8908
    
    8

Any subclass of java.io.Writer can handle writing a String. Again, I suggest you read through the IO tutorial.
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Thanks Joe, i went through the tutorial. It was a nice tutorial to get a hands on. But i think my problem of preserving the line breaks in the string variable into the file still persists.
For e.g.

String fileData = "hi this is
Omk 235 64
ar Pat ka r"


As you can see there are line breaks after "is" and "64" in the value of the String variable fileData .

Now, i try to write this into a file like this: -



Now, there are two problems: -

1) The name of the file is something like this mjn####.txt ...where # is any random digit... i don't know why this happens ? ... Any idea ? ...how can i prevent this ?

2) The contents of the file are :-
hi this isOmk 235 64ar Pat ka r


That means in the contents of the file all the line breaks are skipped! Now there are some blocks of code that i have commented....even those blocks give me the same result .... ....how can i avoid this ? ... please help me!!

Thanks and Regards
Omkar Patkar
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8908
    
    8

How are you getting this to compile?


If I try something like that I get a compile error: "unclosed string literal"
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
ohhh....actually, its like, the "filedata" is a parameter in my program, which gets such a value .....which is to be stored in file. Just for sake of describing i have posted it that way ...otherwise, you can consider, "\n" at the line breaks,

I think this is what we would have written if we wanted to hardcode in our program...

String fileData = "hi this is\nOmk 235 64\nar Pat ka r";

but...i get such value in a parameter.

P.S. I am not sure if "\n" would mean line break ....OR "\r\n" ...i am using windows vista.

Thanks and Regards
Omkar Patkar
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

First of all, the random digits come from your use of the createTempFile() method, the purpose of which is to create new random file names. If you want your file to be called "C:\\Me\\exp\\mjn.txt", then just pass exactly this String to the constructor of FileWriter; don't use createTempFile at all.

Second, yes, the problem is not that the line breaks aren't being preserved; the problem is that Windows doesn't want just line breaks (\n), but also carriage returns (\r). If you're writing your String as a literal in the Java code, then you could use the constant "java.io.File.lineSeparator" instead of a "\n".


[Jess in Action][AskingGoodQuestions]
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 686
Where is the following defined? Was there a typo?
"java.io.File.lineSeparator"


How does the OP know that the 0x0D and/or the 0x0A are not being written to the file? What program is being used to view the file? On windows there Wordpad seems more forgiving if a file doesn't have both at the end of a line.
Notepad wants both.

The following code writes out a string with the 0D0A (\r\n) to the file.
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

Originally posted by Norm Radder:
Where is the following defined? Was there a typo?


I'm guessing that should have been System.getProperty("line.separator").

The simplest way to write out the current new-line character is with a BufferedWriter's newLine() method, or a PrintWriter's println() methods.
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 686
But what if the data already contains a newline or other control chars and you're not wanting to add new ones, but just output what is already in the String.

Thanks for the location of the line.separator value.
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Thank you guys for the reply. But i still have some more doubts: -

I went through the api doc of FileWriter, but there isn't any constructor with String as a parameter. Also, if i create a File object using "new File("C:\\Me\\exp\\mjn.txt")", it will throw FileNotFoundException, since there is no such file! Actually, through my program i want to Create a new file and save the contents of the String into it.

From the inputs i got from you guys, i have realized that, Windows needs both "\r\n" .... BUT, since i have received the value in parameter, .... that is....in a string variable, i don't know ...in which part of the string the line breaks "\r\n" are present!!! .... Therefore, how do i know, when to use the "line.separator" or ".newline()" while writing in the file ?
For example, in the string variable i had posted, the String variable contains the line break twice. SO while writing the value present in the string variable, into the file ... when do i specify bufferedWriter.newLine() ?

Thanks and Regards
Omkar Patkar
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8908
    
    8

Originally posted by omkar patkar:

I went through the api doc of FileWriter, but there isn't any constructor with String as a parameter.

You mean like this one?
The Java Tutorial I pointed you to earlier has examples which demonstrate the use of the string constructor. You must have overlooked them.
Originally posted by omkar patkar:

Also, if i create a File object using "new File("C:\\Me\\exp\\mjn.txt")", it will throw FileNotFoundException, since there is no such file!

The File object is an abstraction of the file system and it is possible to create File instances that refer to paths that don't exist (hence the exists() method). Can you show us a small piece of code that exhibits this behavior?

Originally posted by omkar patkar:

From the inputs i got from you guys, i have realized that, Windows needs both "\r\n" ....

You could either replace all instances of "\n" in the String with "\r\n" or you could just check your output with a program that recognizes Unix-style EOL. I think Wordpad does. Most programmer's editors do as well.
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Ohhh my god ! ..... such a BIG OVERLOOK....actually, i am using jdk 1.4, and not jdk 1.5 .....but even in jdk 1.4, i looked for "FilterWriter" rather than "FileWriter" ....such a BIG mistake....my bad! .....and now its even embarassing !

Well.... i will try with that constructor from FileWriter, and get back to you.

Thanks and Regards
Omkar Patkar
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
.... yeee ! ..... first part is solved as per the FileWriter constructor with String parameter ..... phew ! ....i just can't believe i overlooked it! ....

...now i will try with the second part of the problem.... line breaks and get back to you guys

Thanks and Regards
Omkar Patkar
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Ok, i have written a simple test program for my problem ... here is the program:-




Now the contents of the file Me.txt are as follows: -
This is another example of writing a text file!
BufferedWriter is used in this case ldkfjsdlkfj 23523523523 jskfjasfjkaj
to write this file
...and now the size of this file in terms of length is 106


and this is what i exactly see when i open the file in notepad or the text editor available in eclipse.

But the contents of the file Copy of Me.txt are as follows: -
This is another example of writing a text file!BufferedWriter is used in this case ldkfjsdlkfj 23523523523 jskfjasfjkajto write this file
...and now the size of this file in terms of length is 106


and this is what i exactly see when i open the file in notepad BUT not the text editor available in eclipse or the textarea of the javaranch's post text area.

I think.....i have got the problem in this program ....and i have got a feeling that its around the line:-

stringBuffer.append(readLine+"\n");
readLine = bufferedReader.readLine();

... May be when the reader reads a line it trims off "\r\n" and i explicitly append "\n" at the end .... i hope i am right !!! .....

I don't want to write immediately after reading, .... my requirement is to store the contents read into a string variable and store that variable as a property of an object, ...later retrieve the property and write it in a file. But now it seems, if i do this, i will not be able to write contents of "Me.txt" exactly as it is into "Copy of Me.txt" ....
.... how do i do this ? Please help !

Thanks and Regards
Omkar Patkar
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8908
    
    8

Originally posted by omkar patkar:

... May be when the reader reads a line it trims off "\r\n" and i explicitly append "\n" at the end .... i hope i am right !!!



public String readLine() throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Throws: IOException - If an I/O error occurs

Java API documentation

I don't want to write immediately after reading, .... my requirement is to store the contents read into a string variable


Have a look at StringWriter. You could read from the file and write to StringWriter. You could even wrap StringWriter with PrintWriter so you could use println(), which would add a EOL marker. Of course, the EOL marker is platform dependent, so if you want Unix-style on Windows you'll have to add it manually.
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Thanks Joe, I will try StringWriter....but tell me ... if i read every single character using BufferedReader, will the "read()" function return linebreaks present in the source from which it is reading ? ... Please let me know!

Thanks and Regards
Omkar Patkar
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Hi guys,

I changed my test program a bit and it looks something like this:-



And the good news is....it preserves, all the linebreaks and white space... Whether i open it in notepad or text editor of eclipse ...both the files look identical ...but have i written the program correctly....or will it fail to give desired output for any special characters ?

Thanks and Regards
Omkar Patkar
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
I tried my test program for image file.....but the file created shows a messed up image. ...i tried to debug and realized, that when image file is read, it shows special characters...how do i handle such cases ? .... please help???

Thanks and Regards
Omkar Patkar
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

If you�re working with binary data, not text, you need to use the InputStream and OutputStream classes, or possibly the DataInputStream and DataOutputStream.

If you want to work with the image itself, you could look into the Image I/O classes.
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Hi Carey

Thanks, but i don't want my program to be specific to the type of file....i mean the original file could be: -

text file (.txt)
data file (.dat)
mp3 file (.mp3)
zip file (.zip)
image file (.jpg, .gif)
movie file (.avi)
xml file (.xml)
html file (.html)

.... etc., it could be of any type. I want my program to be generic...would sticking to InputStream a right thing to do ?

Thanks and Regards
Omkar Patkar
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

If you want to work with binary data like images and MP3 files, I do think you need to use InputStream and OutputStream, and byte[] (or ByteArrayOutputStream rather than String.

It depends on exactly what you want to do, though. Some multimedia files will be too large to load into memory completely, and will need a different approach. There's some things in NIO like ByteBuffers that make certain things much easier, too.
omkar patkar
Ranch Hand

Joined: Aug 25, 2005
Posts: 231
Thanks Carey ... i will have a look at ByteBuffers....but is it available in jdk 1.4 ?
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

NIO, including Channels and Buffers, appeared in Java 1.4.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Writing data into file from a String variable