Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

File (String pathname) not working in Java

+3 votes
asked Apr 18, 2021 by Sushant Manandhar (150 points)

I am referencing data.txt but for some reason it's still giving me a FileNotFoundException. I've tried a few variations on the format but still nothing. I can do the rest after the file handling but that itself is giving me a problem

While we're at it, how do I use the toURL(), tried that too but didn't work?


and the data from which I pulled the first line for an example


1 Answer

+1 vote
answered Apr 19, 2021 by Peter Minarik (87,810 points)
edited Apr 21, 2021 by Peter Minarik

First of all, you have to handle exceptions in Java. Either catch them and deal with them or mark your function with a throw statement and let the callers handle the exception.

Since your code is running on a Linux server (not your own machine) the owners made limitations of what you can access and what not. It seems like creating new files is not something you can do. At least not programmatically. Instead, you can add a new file to your project (e.g. "data.txt") and now there's a file with a name you wanted and you can change it to your liking.

Also, when you want to print the content of the "scanned" file, doing "System.out.println(sc);" will do you no good as it prints the string representation of the Scanner object. What you want to do instead is scan line by line and print every one of these scanned lines.

I've fixed your code too:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main
    public static void main(String[] args) {
        String fileName = "data.txt"; // Try "Main.java" instead. ;)
        try {
            Scanner sc = new Scanner(new File(fileName));
            while (sc.hasNextLine())
        } catch(FileNotFoundException e) {
            System.out.println("Could not open '" + fileName + "\'.");
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.