By understanding this code below , you will comphrend both reading from and writing to file concepts in java. I used FileInputStream and FileOutputStream in this code.
package javacream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//Prepare file objects
File fInputFile = new File(strInputFileName);
File fOutputFile = new File(strOutputFileName);
//Prepare read write streams from file objects
FileInputStream fis = new FileInputStream(fInputFile);
FileOutputStream fos = new FileOutputStream(fOutputFile);
int c;
// read from the input file and write to the output file
while ((c = fis.read()) != -1) {
fos.write(c);
}
//we are done , close the streams.
fis.close();
fos.close();
}
public static void main(String[] args) {
try {
// use \\ for windows filenames , otherwise use single /
copyFile("d:\\sample.txt", "d:\\copyof_sample.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Alternatively , you can use FileReader object and BufferedReader. The sample code below counts the number of lines of a given file.
public static int lineCount(String fileName) throws IOException{
// file reader to read the file
FileReader input = new FileReader(fileName);
// Filter FileReader through a BufferedReader to read line by line
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
int count = 0; // Line count
// Read first line
line = bufRead.readLine();
count++;
// Read through file one line at time.
while (line != null){
line = bufRead.readLine();
count++;
}
bufRead.close();
return count;
}


