Some trouble with File I/O [Java]

  • Context: Java 
  • Thread starter Thread starter Enharmonics
  • Start date Start date
  • Tags Tags
    File Java
Click For Summary
SUMMARY

The discussion centers on a Java program designed to read strings from a file and categorize them based on their format. The program successfully writes valid two-word strings to a designated output file but fails to write certain invalid lines to "System.out.txt." The issue arises from the method systemWriter, which creates a new PrintWriter instance each time it is called, potentially leading to file handling issues. The recommendation is to collect all data before writing to files to avoid repeated stream creation.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of file I/O in Java
  • Regular expressions for string manipulation
  • Exception handling in Java
NEXT STEPS
  • Learn about Java BufferedReader and PrintWriter for efficient file handling
  • Explore Java regular expressions for advanced string parsing
  • Investigate best practices for managing file I/O streams in Java
  • Study Java exception handling techniques to improve error management
USEFUL FOR

Java developers, software engineers, and students learning file I/O operations and string manipulation in Java.

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.
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 28 ·
Replies
28
Views
4K
  • · 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
5K
  • · Replies 1 ·
Replies
1
Views
15K