Introduction
In
this blog we will know how to read and write to a file in java.
-
- import java.io.*;
- import java.util.*;
- public class readFile
- {
- public static void main(String arg[])throws Exception
- {
- System.out.print("Provide name of file to read ");
- Scanner sc=new Scanner(System.in);
- String s=sc.next();
-
- FileReader fis=new FileReader(s);
- int x;
- while((x=fis.read())!=-1)
- System.out.print((char)x);
- }
- }
compile
javac
readFile.java
java
readFile
-
- import java.io.*;
- import java.util.*;
- public class writeFile
- {
- public static void main(String arg[])throws Exception
- {
- Scanner sc=new Scanner(System.in);
- System.out.print("Provide file name:");
- String fname=sc.next();
- System.out.print("Provide data to be written:");
- String data=sc.next();
-
- FileWriter fw=new FileWriter(fname,true);
- fw.write(data);
- fw.close();
- }
- }
compile
javac
writeFile.java
java
writeFile