How to take Input/Output from external file in JAVA

Hello guys! I wanna know about how to take Input/Output of test cases stored in external file like “input.txt” and “output.txt” in java? The concept that i can apply in Hackercup or codejam platform. Please don’t suggest command prompt method. I want general method that can easily be used for debugging.

I suggest you to read about fopen . It makes your normal cin to take input from the file specified in its argument and same for cout

The simplest method which I follow is redirection

javac my file.java

java ClassName <input.txt >output.txt

Alternative methods can be using PrintStream, file handling or creating a pipe.

However first method is easiest and widely used.

Hope it helps

I know already this command prompt method. I want you to elaborate 2nd method with input/output details.

There are various methods. You can use InputStream and OutputStream and link them to your file.

import java.io.*;
public class test {
public static void main(String []args)
{
try {
InputStream in=new FileInputStream(“input.txt”);
OutputStream out=new FileOutputStream(“output.txt”);
int x=in.read();
out.write(x);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Alternatively you can use PrintWriter, create a pipe, file handling etc

This gives a good description of what you want to know. Otherwise, just Google your query. There are a lot of references available online.

1 Like
//