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

Inserting data into a file

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

Problem

So, given a file with the following format:


[header]

line of data

line of data

line of data

line of data


[header 2]

line of data

line of data

line of data


...

I add a line of data to a specific header so the result would be:


...

[target header]

line of data

...

new line inserted

The program currently only adds lines but is written so it accepts an input file that lists instructions with the format instruction|[header]|line to add e.g. A|[Passions]|Code Review would add Code Review to the Passions section.

```
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class AdjustList {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("No arguments provided.");
System.exit(1);
}

try (Scanner fileScanner = new Scanner(new File(args[0]))) {
while (fileScanner.hasNextLine()) {
String[] commandParameters = fileScanner.nextLine().split("\\|");
if (commandParameters.length != 3) {
throw new IllegalArgumentException("Invalid parameter format");
}

File targetFile = new File("ImportantList.md");
processCommand(targetFile, commandParameters[0], commandParameters[1], commandParameters[2]);
}
} catch (FileNotFoundException fnfe) {
System.err.println("File doesn't exist / wrong directory");
}
}

private static void processCommand(File file, String instruction, String targetSection, String inputLine) {
boolean taskComplete = false;
StringBuilder fileBuilder = new StringBuilder();

try (Scanner fileScanner = new Scanner(file)) {
if (instruction.equals("A")) { // add
System.out.println("Adding " + inputLine + " to " + targ

Solution

Misleading Message?

if (args.length != 1) {
        System.err.println("No arguments provided.");
        System.exit(1);
    }


So if I have 2 arguments, I get the message No arguments provided. Umm... I provided 2 arguments!
Suggested fix:

Change the above code to:

if (args.length == 0) {
        System.err.println("No arguments provided.");
        System.exit(1);
    }


And you can possible warn the user about only requiring one argument if they provide too much. Something like:

if (args.length > 1) {
        System.out.println("Warning! Too many arguments; only the first one will be considered.");
    }

Code Snippets

if (args.length != 1) {
        System.err.println("No arguments provided.");
        System.exit(1);
    }
if (args.length == 0) {
        System.err.println("No arguments provided.");
        System.exit(1);
    }
if (args.length > 1) {
        System.out.println("Warning! Too many arguments; only the first one will be considered.");
    }

Context

StackExchange Code Review Q#132538, answer score: 2

Revisions (0)

No revisions yet.