Reading / Writing in Java

Friends reading & writing operation in java is very easy.

To write to a file :

File f = new File(“/location/of/file.txt”);
if(!f.exists())
{
f.createNewFile();
}
FileWriter fw = new FileWriter(f,true); //true meaning allow append
BufferedWriter wr = new BufferedWriter(fw);
wr.write(token);
wr.close();
fw.close();

To read file:

String data=””;

String final_data=””;

File f = new File(“/location/of/file.txt”);
if (f.exists()) {
FileReader fr = new FileReader(f);
BufferedReader reader = new BufferedReader(fr);
while ((data = reader.readLine()) != null) {
final_data += data;
}

reader.close();
fr.close();

 

To read from keyboard

Read the input 3 times after pressing enter each.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i=0;
String [] data = new String[3];
while(i<3)
{
data[i] = br.readLine();
i++;
}

 

Advertisements

One thought on “Reading / Writing in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s