freetimestudys@gmail.com          +91-7097633380
  Login Here                        

FileInputStream read single character

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\text.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}  

intput and output

output:w

FileInputStream read all characters

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}  

intput and output

output:Welcome to freetimestudy

copy File

import java.io.*;
class Test
{
static FileInputStream fis;
static FileOutputStream fos;
public static void main(String[] args)
{
try{
fis=new FileInputStream("so.txt");
fos=new FileOutputStream("de.txt");
int c;
while ((c=fis.read())!=-1)
{
fos.write(c);
}
fis.close();
fos.close();
}
catch(IOException io)
{
System.out.println("getting IOException");
}
}
}

intput and output

output:copying data do.txt to de.txt

file append program

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\text.txt",true);
String s="Welcome to freetimestudy.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close(); 
}catch(Exception e){System.out.println(e);}
}
}  

intput and output

output:text file allredy exit wite data other vise create and write file

split a file into multiple Chunk

package bb;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Scanner;

public class FileRead {
public static void main(String args[])throws IOException {
File file=new File("E:/mail.txt");
int counter = 1;
int sizeOfChunk = 1024*1;
String eof = System.lineSeparator();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String name = file.getName();
String line = br.readLine();
while (line != null) {
File newFile = new File(file.getParent(), name + "."
+ String.format("%03d", counter++));
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(newFile))) {
int fileSize = 0;
while (line != null) {
byte[] bytes = (line + eof).getBytes(Charset.defaultCharset());
if (fileSize + bytes.length > sizeOfChunk)
break;
out.write(bytes);
fileSize += bytes.length;
line = br.readLine();
}
}
System.out.println(newFile);
}
}

}
}

intput and output

output:get more files