//Creating txt file
import java.io.*;
public class CreateFile{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file name to create : ");
String file_name = in.readLine();
File file = new File(file_name);
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
System.exit(0);
}
else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.close();
System.out.println("File created successfully.");
}
}
}
// Writting to a file
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Random Access file
import java.io.*;
public class RandAccessFile{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String str = in.readLine();
File file = new File(str);
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try{
//Open the file for both reading and writing
RandomAccessFile rand = new RandomAccessFile(file,"rw");
char ch = rand.readChar(); //Read a character
rand.seek(file.length()); //Seek to end of file
rand.writeChars("Namaste India,"); //Write end of file
rand.close();
System.out.println("Successfully");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
This are few program mes which show creating writting and using random file.
For more detail refer java.io package