.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Reading and writing file in java

Posted By:satyapriyanayak       Posted Date: June 30, 2014    Points: 40    Category: Javascript    URL: http://www.dotnetspark.com  

In this Code Snippets we will know how to read and write to a file in java.
 

/*File reading by using FileInputStream/FileReader*/
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();
//FileInputStream fis=new  FileInputStream(s);
FileReader fis=new  FileReader(s);
int x;
while((x=fis.read())!=-1)
System.out.print((char)x);
}
}

compile

javac readFile.java
java readFile

/*File writing by using FileOutputStream/FileWriter*/
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();
//To use FileWriter
 FileWriter fw=new FileWriter(fname,true);
 fw.write(data);
 fw.close();
}
}

compile

javac writeFile.java
java writeFile
 


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend