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.

how can I read the data inside a .txt file which I have created in the data using online gdbcompiler in Java?

+9 votes
asked Oct 18, 2024 by BALASUBRAMANIAM A/L N.RAMU B04STM23F006 (210 points)
my code :

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

public class BacaFail{
public static void main(String []args) throws Exception{

        File f=new File("data.txt");
        Scanner sc=new Scanner(f);
        
        while(sc.hasNextLine()){
            System.out.println(sc.nextLine());
        }
    }
}

2 Answers

0 votes
answered Oct 21, 2024 by Peter Minarik (101,340 points)
The file you create (data.txt) will be in your project listed alongside the source file. This way, you can manually look at it, just like at your code files.

Alternatively, you can access it just like in your example: from code.
0 votes
answered Dec 2, 2024 by ???? ???? (220 points)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {
        // Change this to the name of your file
        File file = new File("data.txt");

        try (Scanner scanner = new Scanner(file)) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line); // Print each line
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...