Joshua Oliphant
Joshua Oliphant

Reputation: 932

Failing to print out contents of a file

I'm trying to print out the contents of the file. When I run the program, it doesn't do anything and I'm having trouble figuring out why.

public static void main(String[] args) {

    String fileName = "goog.csv";

    File file = new File(fileName);

    try {
        Scanner inputStream = new Scanner(file);
        while(inputStream.hasNext()){
            String data = inputStream.next();
            System.out.println(data + "***");
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Upvotes: 1

Views: 106

Answers (3)

Harshal Patil
Harshal Patil

Reputation: 6759

Need to give full path of goog.csv file. Put goog.csv file in workspace .metadata directory then give full path of your file it will giving output because i tried your code on my system. I just change your goog.csv file with mine firmpicture.csv file.

public static void main(String[] args) {

    String fileName = "FilePath";

    File file = new File(fileName);

    try {
        Scanner inputStream = new Scanner(file);
        while(inputStream.hasNext()){
            String data = inputStream.next();
            System.out.println(data + "***");
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Upvotes: 4

blazy
blazy

Reputation: 338

You need to specify the full path to the file, unless it exists in the present directory.

Upvotes: 0

Shrikant Kakani
Shrikant Kakani

Reputation: 1561

Try this:

public static void main(String a[]) {

       String fileName = "goog.csv";
       File f = new File(fileName);
       String data = "";

       if(f.exists()) {         
        try {
            BufferedReader br = new BufferedReader(new FileReader(f));
            while((data= br.readLine()) != null) {
                if(!(data.length() == 0))
                    System.out.println(data);
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } 
    } else {
        System.out.println("The file does not exists !!!");
    }
 }

Upvotes: -1

Related Questions