I made two unix cat examples in Java but both were very slow compared to C++
[Java Example 1]
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedCat {
public static void main(String[] args) throws IOException {
String path = args[0];
FileReader file = new FileReader(path);
BufferedReader buffReader = new BufferedReader(file);
int c = buffReader.read();
while(c != -1) {
System.out.print((char)c);
c = buffReader.read();
}
buffReader.close();
}
}
[Java Example 2]
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ScannerCat {
public static void main(String[] args) throws IOException {
String path = args[0];
Scanner scanner = new Scanner(new File(path));
while(scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
[C++ Example 3 ]
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char **argv) {
string line;
ifstream myfile (argv[1]);
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Example two is much faster than the first, but it's not quite like C++ I'm using this file and file2 as a test, As I'm a beginner in java, I believe that I don't know how to correctly use the IO.
I know java is a language that compiles to bytecode and runs in the JVM and it won't perform as high as C++, but I'm pretty sure the problem lies in the implementation of my simple cat. So i want to helps you guys on how to use IO in java effectively