I am going to show example which shows how to read a file in Java.
If you want to read some file you should start with . This class is a concrete subclass of . It provides an input stream connected to a particular file.
Example:
package tutorial;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
* This class shows how to read a file and show it in system console
* @author The Developer's Info
*/
public class Main {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
try {
String workingDirectory = System.getProperty("user.dir");
File fileDir = new File(workingDirectory, "src/tutorial");
File file = new File(fileDir, "Main.java");
fileInputStream = new FileInputStream(file);
show(fileInputStream, System.out);
} catch (IOException ex) {
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException ex) {}
}
System.out.println();
}
/**
* This method shows Main.java content in console
* @param fin input stream
* @param out output stream
* @throws IOException
*/
private static void show(FileInputStream fin, PrintStream out) throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = fin.read(buffer);
if (bytesRead == -1) {
break;
}
out.write(buffer, 0, bytesRead);
}
}
}
Main method here is show(). It is very simple method. In general Java allows to work with all things very easy.
Related posts:

Recent Comments