Some trouble with File I/O [Java]

  • Java
  • Thread starter Enharmonics
  • Start date
  • Tags
    File Java
In summary, the speaker is trying to write Strings to files in Java and is having trouble with the formatting. They have successfully implemented writing to one file but are encountering issues with writing to the System.out file. They suspect that the issue may be related to closing the output stream after using it in the try-catch block. However, it is suggested that for a simple program like this, it would be better to collect all of the data and then write to each file, as passing readers and writers into a method can lead to errors.
  • #1
Enharmonics
29
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
  • #2
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.
 

FAQ: Some trouble with File I/O [Java]

What is File I/O in Java?

File I/O (Input/Output) in Java refers to the process of reading from and writing to files on a computer's storage system. It allows Java programs to interact with external files and perform operations such as reading data from a file or writing data to a file.

How do I read from a file in Java?

To read from a file in Java, you can use the FileInputStream class to open the file, and then use the read() method to read the contents of the file into a buffer. You can then manipulate the data in the buffer as needed.

How do I write to a file in Java?

To write to a file in Java, you can use the FileOutputStream class to open the file, and then use the write() method to write data to the file. You can also use the BufferedWriter class to write data to a file using a BufferedWriter object.

What are some common errors when dealing with File I/O in Java?

Some common errors when dealing with File I/O in Java include FileNotFoundException, which occurs when the specified file cannot be found, and IOException, which can occur when there is an error while reading from or writing to a file.

How can I handle exceptions when working with File I/O in Java?

You can handle exceptions when working with File I/O in Java by using try-catch blocks to catch and handle any errors that may occur. It is important to properly handle exceptions to prevent your program from crashing and to provide useful error messages to the user.

Similar threads

Replies
4
Views
3K
Replies
3
Views
2K
Replies
4
Views
976
Replies
16
Views
5K
Replies
5
Views
2K
Replies
4
Views
2K
Replies
1
Views
2K
Replies
1
Views
14K
Back
Top