HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Writing and reading of character files

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readingwritingcharacterfilesand

Problem

I've made the following Java-class just for getting some practice with the creation and reading of files.

```
package modul;

import static java.lang.System.*;
import java.io.*;

public class Sandbox {
public static void main (String[] args) {

// I found out that the project directory is the
// working directory by default.
// Is there a way to change the working directory in Java?
// So that all instructions become relative to that directory.
String currentDir = System.getProperty("user.dir") + "/src/modul/";
String fileName = "lorem.txt";

try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(currentDir + fileName)));

// Write a few lines of dummy-text ...
writer.println("The very first line of text.");
writer.println("----------------------------");
writer.println("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.");
writer.println("Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.");
writer.println("In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.");

// Is it enough just closing the PrintWriter?
// What's about the BufferedReader and the FileReader?
// Are they closed automatically?
writer.close();

// Now open the created file. Read and print it's
// content to stdout.
BufferedReader reader = new BufferedReader(new FileReader(currentDir + fileName));
String line;
int lineNumber = 0;

while ((line = reader.readLine()) != null) {
out.println(++lineNumber + ": " + line);
}

// Is it fair enough just closing the Reader?
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace

Solution

Nice first implementation.

Autoclosable / try-with-resources

Please consider the AutoClosable feature from Java 8 7 to use in a try-with-resources block. See here for more detail.

Split try blocks to be as small as possible

Try (ha :) to isolate as much code as possible in your try blocks. You can make better error handling that way.

Reuse classes

Always search the Java API for nice helper classes, in this case there is a LineNumberReader that will do what you want to do

Changing working directory

I really hate it when programs do this. You will (on exit) end up in a different locatation, unless you put effort in switching back, which makes you program more difficult.

Best thing to do it to establish a 'base' directory, and use relative paths from there. Just like you did.

Proposed solution

try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(currentDir + fileName))))
    {

        // Write a few lines of dummy-text ...
        writer.println("The very first line of text.");
        writer.println("----------------------------");
        writer.println("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.");
        writer.println("Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.");
        writer.println("In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

   try(LineNumberReader lineLeader = new LineNumberReader( new BufferedReader(new FileReader(currentDir + fileName))))
    {
        // Now open the created file. Read and print it's 
        //  content to stdout.in 
        String line;

        while ((line = lineLeader.readLine()) != null) {
            out.println(lineLeader.getLineNumber() + ": " + line);
        }
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

Code Snippets

try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(currentDir + fileName))))
    {

        // Write a few lines of dummy-text ...
        writer.println("The very first line of text.");
        writer.println("----------------------------");
        writer.println("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.");
        writer.println("Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.");
        writer.println("In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

   try(LineNumberReader lineLeader = new LineNumberReader( new BufferedReader(new FileReader(currentDir + fileName))))
    {
        // Now open the created file. Read and print it's 
        //  content to stdout.in 
        String line;

        while ((line = lineLeader.readLine()) != null) {
            out.println(lineLeader.getLineNumber() + ": " + line);
        }
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

Context

StackExchange Code Review Q#162581, answer score: 9

Revisions (0)

No revisions yet.