smirli smirli - 6 months ago 20
Java Question

Filereader Java Class

I'm looking for a way to read an entire file.
I need this for a java project. I know about the BufferedReader but I've never written code like that. I mean the entire exception, try catch...ect stuff
I've only been into the basics so far.
An example model would be appreciated

Answer

this are the classes that I usually use for input in my java projects. I recommad to store these classes because you are going to need them more often if you keep programming but dtill I want you to go throu the code and try to understand it. Else tthis doen't help you at all.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public final class Terminal {

    private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    private Terminal() {
    }

    public static void printLine(String out) {
        System.out.println(out);
    }

    public static String readLine() {
        try {
            return in.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

This is the second class

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public final class FileInput {


    private FileInput() {
    }


    public static String[] read(String file) {
        StringBuilder result = new StringBuilder();
        FileReader in = null;
        try {
            in = new FileReader(file);
        } catch (FileNotFoundException e) {
            Terminal.printLine("Error, " + e.getMessage());
            System.exit(1);
        }
        BufferedReader reader = new BufferedReader(in);
        try {
            String line = reader.readLine();
            while (line != null) {
                result.append(line);
                line = reader.readLine();
                if (line != null) {
                    result.append("\n");
                }
            }
        } catch (IOException e) {
            Terminal.printLine("Error, " + e.getMessage());
            System.exit(1);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        return result.toString().split("\n");
    }
}

`

Comments