Frage

Can someone take a look at the code below and tell me why it isn't displaying an error message if args[0] is empty? The program works fine if the file entered is a duplicate, displaying the file already exists message. Java is throwing an ArrayIndexOutOfBounds error on me. I've tried adding that exception to the code as well but nothing is picking it up.

import java.io.*;
import java.util.*;
public class inputTest{
    public static void main(String[] args) throws IOException{
    if(args.length() == 0){
    System.out.println("Please enter a correct text file name!");
    System.exit(1);
    }
    java.io.File file = new java.io.File(args[0]);
    if (file.exists()){
        System.out.println("This file already exists!"); // If file exists, throw exception
        System.exit(1);
    }
    // Create a file    
    java.io.PrintWriter output = new java.io.PrintWriter(file);

    }
}

Also, is there a way to ensure the file being entered at the command prompt is of .txt variety?

War es hilfreich?

Lösung

This code will give comilation problem

Cannot invoke length() on the array type String[]

change to

public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    if(args.length == 0){
        System.out.println("Please enter a correct text file name!");
        System.exit(1);
    }
    java.io.File file = new java.io.File(args[0]);
    if (file.exists()){
        System.out.println("This file already exists!"); // If file exists, throw exception
        System.exit(1);
    }
    // Create a file    

    java.io.PrintWriter output = new java.io.PrintWriter(file);
}

Andere Tipps

Consider using Apache Commons ArrayUtils isEmpty() to test for emptiness of the Array without worrying about dealing with null array vs. empty array.

You can also use Apache Commons IO FilenameUtils getExtension() to get the extension of the file.

Though this won't help you master the concepts of Java, you may now become familiar with one of main sets of libraries used by Java devs, and with how to add libraries to your project.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top