Java-Writing to a file

import java.io.*;

public class WriteFile {
public static void main(String args[]) throws IOException {
if (args.length != 0) {
File file = new File(args[0]);

if (file.exists()) {
System.out.print("This file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if(response == 'N'||response =='n') {
// if you do not want to overwrite the file.
System.exit(0); // stop program
}
} else {
System.out.print("Creating new file: " + args[0] + "...");
}

System.out.println();
System.out.println(
"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);
System.out.println(
"--------------------------------------------------------------------------------");

FileOutputStream output_file = new FileOutputStream(file); // output file.
boolean continue_write = true;
byte[] data; // byte array to which the data is read into.
while (continue_write) {
// continue reading lines till the user types '~' and ENTER.
data = new BufferedReader(
new InputStreamReader(System.in)).readLine().getBytes();
if (data.length == 1 && ((char)data[0]) == '~') {// if end-of-file
continue_write = false;
} else {// if not end-of-file
output_file.write(data);
output_file.write('\n');
}
}
System.out.println(
"--------------------------------------------------------------------------------");
output_file.close();
} else {//end of while
System.out.println("Usage: java WriteFile ");
}
}
}



/*public class WriteFile
{
public static void main(String args[]) throws IOException
{
if(args.length!=0)
{
File file=new File(args[0]);

if(file.exists())
{
System.out.print("This file already exists. Overwrite? (y/n): ");
int response=System.in.read();
if(response=='N'||response=='n')
// if you do not want to overwrite the file.
{
System.exit(0); // stop program
}
}
else
System.out.print("Creating new file: " + args[0] + "...");


System.out.println();
System.out.println(
"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);
System.out.println(
"--------------------------------------------------------------------------------");

PrintWriter output_file=new PrintWriter(
new FileOutputStream(file), true); // output file.
boolean continue_write=true;
String line;
while(continue_write)
// continue reading lines till the user types '~' and ENTER.
{
line=new BufferedReader(new InputStreamReader(System.in)).readLine();
if(line.length()==1 && line.equals("~")) // if end-of-file
continue_write=false;
else // if not end-of-file
output_file.println(line);
}
System.out.println(
“--------------------------------------------------------------------------------“);
output_file.close();
}
else
System.out.println(“Usage: java WriteFile ”);
}
}*/

Post a Comment

0 Comments