Dear Friends,
i want to write the content into a file from cmd.im able to create the file and read content from cmd but not able to write the content into the file
thanks in advance
Printable View
Dear Friends,
i want to write the content into a file from cmd.im able to create the file and read content from cmd but not able to write the content into the file
thanks in advance
So, what's your code then?
Tolls thanx for replying
Here is the code ...of what im trying to do
Code:import java.util.Scanner;
import java.io.*;
public class Scann
{
public static void main(String [] args) throws Exception
{
System.out.println("Enter 0 to exit:");
System.out.println("Enter your name:");
Scanner sc = null;
while(true)
{
File objFile = new File("Hello.txt");
FileWriter objWrite = new FileWriter(objFile);
//Writer objWriter = new BufferedWriter(new FileWriter (objFile));
//FileOutputStream os = new FileOutputStream(objFile);
sc = new Scanner(System.in);
String name = sc.nextLine();
if(!name.equals("0"))
{
if(sc.hasNextLine())
{
objWrite.write(name);
}
}
else
{
System.exit(0);
}
}
}
}
You have a while loop, and what's happening there?
OK, so in the above code (which is run each time around the loop) you are opening a file, creating a new Scanner, reading a line from the command line (in), then (assuming it's not "0") seeing if there's another line to read in. If so, you write out the first line you read (name).Code:File objFile = new File("Hello.txt");
FileWriter objWrite = new FileWriter(objFile);
sc = new Scanner(System.in);
String name = sc.nextLine();
if(!name.equals("0"))
{
if(sc.hasNextLine())
{
objWrite.write(name);
}
}
else
{
System.exit(0);
}
Everytime round the loop.
So first off, do you think you need to open the file each time?
Second do you think that check on hasNextLine() is correct, after you've already read in a line?
Third, do you think you need to create a new Scanner each time?
yeah Tolls I agree with u that don't have to open the file ,and also no need to create the object of the scanner again and again. When Im printing name then it is printing what ever content im entering from the cmd. but not able to write that into the file.so how to write the content into the file. ?
So, what does the code look like now?
code is same i have just removed that code from there
System.out.println("Enter 0 to exit:");
System.out.println("Enter your name:");
Scanner sc = null;
File objFile = new File("Hello.txt");
FileWriter objWrite = new FileWriter(objFile);
sc = new Scanner(System.in);
String name = sc.nextLine();
if(!name.equals("0"))
{
objWrite.write(name);
}
else
{
System.exit(0);
}
Do you actually close the file writer?
thanks Tolls
:)
it is working now. I was not closing the file.
Please use code tags next time when you are posting code segments. Unformated codes are really hard to read. :)
And also if you've solve the problem, then please mark the thread solved from tools menu.