Lena Monika Marshall Lena Monika Marshall - 7 months ago 48
Java Question

Reading multiple files using BufferedReader(with String[] args)

I want to read texts from two or more files using using main methods array. Is it possible? (my code could be a little strange because I'm a beginner)

Here is my code.

public static void main(String[] args) throws IOException {
if(args.length != 1)
{
System.out.println("wrong number of arguments");
System.exit(1);
}
args[0] = "data.txt";
args[1] = "data2.txt";

BufferedReader file = new BufferedReader(new FileReader(args[0],args[1]));
int NumberofRows =0, NumberofCharacter =0;
while(true)
{
String row = file.readLine();
if(row == null)
break;
NumberofRows++;
NumberofCharacter = NumberofCharacter + row.length();

}
System.out.println("The files "+" data.txt " + " and " "data2.txt "+ "contains "+ NumberofRows+ "rows and NumberofCharacter contains"+
NumberofCharacter +" character");

file.close();

Answer

@Lena : i don't understand why do you affect values to args[] in the main method ?

args[0] = "data.txt";
args[1] = "data2.txt";

Instead you can pass the files' names in the args[] while you execute your main, and test if args[].length < 1, cause args[].length != 1 will always be true if you want to read two files or more. So as @ugurdonmez says : You can create a BufferedReader array with a equal size of args.

    public static void main(String[] args)throws IOException {
                if(args.length <1)
                {
                    System.out.println("wrong number of arguments");
                    System.exit(1);
                }
                for(int i=0; i<args.length; i++)
                {
                   BufferedReader file = new BufferedReader(new FileReader(args[i]));
                   int NumberofRows =0, NumberofCharacter =0;
                   while(row = file.readLine()) !=null)
                   {
                      String row = file.readLine();
                      NumberofRows++;
                      NumberofCharacter = NumberofCharacter + row.length();
                    }
                }
                System.out.println("The files "+" data.txt " + " and " "data2.txt "+ "contains "+ NumberofRows+ "rows and  NumberofCharacter  contains"+
        NumberofCharacter +" character");
               file.close();
            }
    }
Comments