• Post Reply Bookmark Topic Watch Topic
  • New Topic

writing a string to a file in diff directory  RSS feed

 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everbody .. Greetings from Ashish as this is my first posting on javaranch though I have been following it for sometime now.
My question is simple. Following code is able to create myfile.txt in CURRENT FOLDER ( i.e where my FileOutputDemo resides).
My question is if I want to put it in a different folder how shud I go abt... becoz if I simply say
out = new FileOutputStream("c:\test\myfile.txt");
it gives compilation error.
thks
ash
------- here goes the code --------
import java.io.*;
class FileOutputDemo
{
public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );

p.println ("This is written to a file");
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error you are getting is 'Invalid Escape Character'. In Java \ is the escape charater that is use to indicate that the next character is a special character.
\t - tab
\" - double quote
\' - single quote
\r - line feed etc...
If you really want (and in your case you do) a \ in your string, you have to use the escape code for it which is \\. So, you code should be
out = new FileOutputStream("c:\\test\\myfile.txt");
Hope this clears things up
 
Ashish Agnihotri
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks .. its working fine
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!