HTML Java

Java Write File


How to write into the File ?

There are 4 options to write data into file.


1. FileWriter

Example

package com.IOFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileUsingFileWriter {

public static void main(String[] args) {

String write_Data = " This is tutoiral for java beginners";
String file_Path = "/home/codersarts/java_tutorial.txt";
File file = new File(file_Path);
FileWriter fr = null;
try {
fr = new FileWriter(file);
fr.write(write_Data);
System.out.println("Data sucessfully written into file");
} catch (IOException e) {
e.printStackTrace();
}finally{
//close resources
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Output

Data sucessfully written into file



2. Buffered Writer

Example

package com.IOFile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileUsingBufferedWritter {

public static void main(String[] args) {

int noOfLines = 10;
String write_Data = " This is tutoiral for java beginners";
String file_Path = "/home/codersarts/java_tutorial1.txt";
File file = new File(file_Path);

FileWriter fr = null;
BufferedWriter br = null;
String dataWithNewLine=write_Data+System.getProperty("line.separator");
try{
fr = new FileWriter(file);
br = new BufferedWriter(fr);
for(int i = noOfLines; i>0; i--){
br.write(dataWithNewLine);
}
System.out.println("Data sucessfully written into file");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

}

Output

Data sucessfully written into file



3. File OutputStream

Example

package com.IOFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class WriteFileUsingFileOutputStream {

public static void main(String[] args) {

String write_Data = " This is tutoiral for java beginners";
String file_Path = "/home/codersarts/java_tutorial2.txt";
File file = new File(file_Path);
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(write_Data.getBytes(), 0, write_Data.length());
System.out.println("Data sucessfully written into file");
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

}

Output

Data sucessfully written into file



4. Files

Example

package com.IOFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteFileUsingFiles {

public static void main(String[] args) {

String write_Data = " This is tutoiral for java beginners";
String file_Path = "/home/codersarts/java_tutorial3.txt";

try {
Files.write(Paths.get(file_Path), write_Data.getBytes());
System.out.println("Data sucessfully written into file");
} catch (IOException e) {
e.printStackTrace();
}

}

}

Output

Data sucessfully written into file



InputOutputStream

In ‘c’ program is directly connected to I/O devices but in c++/Java not directly they use medium to connect program with I/O devices and this medium is nothing but stream. In network data goes in form of stream and stream is a flow of data in form of bytes. Actual implementation of this concept is in Socket Programming,JDBC connectivity and madvance level .all the stream classes in Java is inside

There is no Stream classes in java.io.Stream both of these are logical categorization of Stream class. InputStream and OutputStream is the root class of bytestream and Reader and writer are the roots clas of Character stream. InputStream has method read() and OutputStream has write() method and these are the abstract class so the implementation of this method is provided by the different classes . In java whenever you want to read data from I/O device then you don’t need to go to I/O devices You hava to go to I/O streams like input stream work is to attach with input device and from that you can bring data into our program and like that in OutputStream



File Reading and Writing Example

Example

package com.IOFile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileReadingWriting {

public static void main(String[] args) throws IOException {

String write_Data = " This is tutorial for java Advance";
FileOutputStream fos = new FileOutputStream("/home/codersarts/java_tutorial2.txt",true);
//fos write data in form of bytes
byte[] b = write_Data.getBytes();
for(int i=0;i< b.length;i++) {
fos.write(b[i]);
}

FileInputStream fis = new FileInputStream("/home/codersarts/java_tutorial2.txt");
while(true) {
int index = fis.read();
if(index==-1)
break;
System.out.print((char)index);
}
}

}

Output

This is tutorial for java Advance

Note: index ==-1 is check for end of file. read() method will read 1 bytes and return its ASCII value if we will print the index value then it will print integers so we need to ypecast in the char and we will pass true while giving file name becasue it always open in update mode if we not pass true and if twice we run the program then it will delete old data and then write new data if we pass true then it open file in append mode its write after the old data . Whenever we read and write data through FileInputStream and FileOutputStream then our application performance decrase it reads byte by byte so to increase the performance we can use byteArrayStream or any other Stream classes.



ByteArrayStream Reading Writing From File Example

Example

package com.IOFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileReadWriteByteArrayStream {

public static void main(String[] args) throws IOException {

String write_Data = " This is tutorial for java Advance";
FileOutputStream fos = new FileOutputStream("/home/codersarts/Desktop/java_tutorial2.txt");
ByteArrayOutputStream bout= new ByteArrayOutputStream();
byte[] b = write_Data.getBytes();
bout.write(b);
bout.writeTo(fos);

byte[] br = bout.toByteArray();
ByteArrayInputStream bin= new ByteArrayInputStream(br);
Timer.startTimer();
while(true) {
int index = bin.read();
if(index==-1)
break;
System.out.print((char)index);
}
Timer.stopTimer();

}

}


Timer class

To check the performance between ByteArrayI/OStream and BufferedI/Ostream

Example

package com.IOFile;

public class Timer {

static long startTime,endTime;

public static void startTimer() {
startTime = System.nanoTime();
}
public static void stopTimer() {
endTime = System.nanoTime();
System.out.println("Total Time : "+(endTime-startTime));
}

}

Output

This is tutorial for java AdvanceTotal Time : 1310627



BufferedStream Reading Writng From File Example

Example

package com.IOFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ReadWriteUsingBufferedStream {

public static void main(String[] args) throws IOException {

String write_Data = " This is tutorial for java Advance";
FileOutputStream fos = new FileOutputStream("/home/codersarts/Desktop/java_tutorial1.txt");
BufferedOutputStream bout= new BufferedOutputStream(fos);
byte[] b = write_Data.getBytes();
bout.write(b);
bout.flush();

FileInputStream fin = new FileInputStream("/home/codersarts/Desktop/java_tutorial1.txt");
BufferedInputStream bin= new BufferedInputStream(fin);
Timer.startTimer();
while(true) {
int index = bin.read();
if(index==-1)
break;
System.out.print((char)index);
}
Timer.stopTimer();
}
}

Output

This is tutorial for java AdvanceTotal Time : 1713560