Search code examples
filefile-iotestcase

How do I create a input file(i.e .in file) in Java?


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class Checkfile
{
    public static void main(String args[]) throws IOException
    {
        OutputStream os = new FileOutputStream("A.in");
        Random rand = new Random();
        int t = rand.nextInt(100);
        os.write(t);
        //System.out.println(t);
        while (t-- > 0)
        {
            int y=rand.nextInt(3000);
            os.write(y);
        }
    }
}

I am getting unusual numbers instead of Integer.I think they are Hexadecimal numbers. I am here trying to write a test case Generator for a competitive programming question. I basically want to write the below C++ code in Java-

#include <bits/stdc++.h>
using namespace std;
int main(void)
{
    freopen("n1.in","w",stdout);
    srand(5);
    int t=rand()%99+1;
    assert(t<=100 && t>=1);
    cout<<t<<endl;

    while(t--)
    {
        int n=rand()%99+3;
        assert(n<=100 && n>=3);
        cout<<n<<endl;
    }
}

Thanks in Advance!


Solution

  • After a lot of searching I found out that the only thing wrong here is that we cannot write a integer or any other data type other than String directly into a file. All other data types go into the file in binary format.