Java Some trouble with File I/O [Java]

  • Thread starter Thread starter Enharmonics
  • Start date Start date
  • Tags Tags
    File Java
Click For Summary
The discussion focuses on a Java program that processes text files by separating lines into two categories based on their format. The code successfully writes valid two-word lines to one output file but fails to write certain invalid lines to another file, only capturing one specific invalid line. The issue may stem from how the PrintWriter is managed, particularly regarding its closing after each write operation, which could lead to the output stream being in a bad state. Suggestions include collecting all data before writing to the files and ensuring proper management of the input/output streams. Overall, the program needs adjustments to handle invalid lines correctly and maintain the integrity of the output streams.
Enharmonics
Messages
29
Reaction score
2
I'm trying to write Strings to files in Java.

Basically, I'm supposed to read from a file containing text (assumed to be strings). For each line of text,
if the String has the format word1 word2 (that is, if it's two words), I have to write it to one file (a list of names), whereas if it doesn't have that format, I have to write it to another file, which is supposed to be called System.out (with the extension .txt)

I made a file and wrote some stuff on it to test my code with. Here's what it contains:

Prima Secunda
First Second
Un Deux
Uno Dos
Ein Zwei
This line is not valid
Neither \.! is this |||; one
Uno Due
This should not be written

I've got the list of names part working just fine. The names get written to the output file as they should:

P.Secunda
F.Second
U.Deux
U.Dos
E.Zwei
U.Due

but when writing to the System.out file, only this line gets written:

Neither \.! is this |||; one

So the lines formatted like regular sentences ("This should not be written", etc) get skipped. I'm not sure why this is. Here's some excerpts from my code:
Java:
public static void processData(BufferedReader inputFile, PrintWriter outputFile)
    {
      
        // A modified version of
        // the algorithm shown
        // on the class page.
      
        String inputLine = null;
      
        try
        {
            // Do/while loop that processes
            // each line taken from the file.
            // First it checks whether the
            // line has the format word1 word2

            while ((inputLine = inputFile.readLine()) != null)
            {              
              
                // Splits the line into tokens,
                // taking the delimiter to be
                // anything that is not an
                // upper or lowercase letter
                // or the tab character (\t)
                // in groups of at least one
                // (using the regex [^a-zA-Z]+)
              
                String[] tokens = inputLine.split("[^a-zA-Z\t]+");
              
                // REMOVE LINES 215-216
                System.out.println("inputLine is: " + inputLine);
                System.out.println("The length of tokens is: " + tokens.length);
              
                // If the line has the format
                // word1 word2, the outputWriter
                // method is invoked to process
                // the words and write them to
                // the output file
              
                if (tokens.length == 2){
                    outputWriter(tokens, outputFile);
                }
              
                // Otherwise, the systemWriter
                // method is invoked to write
                // the line to the System.out file
              
                // REMOVE LINE 234
                else{
                    System.out.println("ENTERED SYSTEMWRITER TREE AT: " + inputLine);
                    systemWriter(tokens);
                }
            }
        }

// Catch block that prints
        // the name of the exception
        // and the line it occurred on
        // to the console
        catch (IOException ex)
        {
            System.out.println(ex + " on line: "
                    + inputLine);
        }
    }

// Auxiliary method that writes
    // lines that do not conform
    // to the format specified
    // by the instructions to the
    // System.out file

public static void systemWriter(String[] tokens)
    {
        // REMOVE LINES 297-303
      
        System.out.println("Tokens contains: ");
      
        for (String currentToken : tokens)
        {
            System.out.println(currentToken + " ");
        }
      
        File systemOutput = new File("System.out.txt");
      
        // Here we create a PrintWriter
        // to write to the System.out
        // file. Note that this does NOT
        // create the file itself, only
        // an object that manipulates it
        // Therefore there is no problem
        // in repeatedly creating the
        // systemFile instance each time this
        // method is invoked
      
        try
        {
            PrintWriter systemFile = new PrintWriter(new FileWriter(systemOutput));
          
            // As requested by instructions,
            // this message let's the user
            // know that the line in question
            // does not have the format word1
            // word2
          
            systemFile.println("The following line does not have the"
                    + " format word1 word2:");
            for (String currentWord : tokens)
                systemFile.print(currentWord + " ");
          
            // Close the System.out file after modifying it
            systemFile.close();
        }
      
        catch (IOException ex)
        {
            System.out.println("Failed to create System.out file!");
        }  
    }

Does this maybe have something to do with my closing the output stream after using it in the try-catch block?
 
Technology news on Phys.org
For a simple program like this, it would be better to collect all of the data that you're going to write and then write to each of the files. Passing readers and writers into a method is a good way to have them get into a bad state.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 28 ·
Replies
28
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 4 ·
Replies
4
Views
1K
  • · Replies 16 ·
Replies
16
Views
5K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 1 ·
Replies
1
Views
15K