Question

I'm trying to read in a file and then write out to a new file, whereby the uppercase characters from the input textfile are then changed to lowercase in the new output file. The file will read and write without the if loop fine, then when I try to implement the if loop to alter the case the output file prints blank. Any help would be greatly appreciated.

import java.io.*;

public class TextFile {
    public static void main (String[] args) throws IOException {
                File file1 = new File("intext.txt");
                File file2 = new File("outtext.txt"); 
                char CharCounter = 0;       
                BufferedReader in = (new BufferedReader(newFileReader(file1)));
                PrintWriter out = (new PrintWriter(new FileWriter(file2)));

                int ch;
                while ((ch = in.read()) != -1)

                    if (Character.isUpperCase(CharCounter)){
                        Character.toLowerCase(CharCounter);
                        out.write(ch);
                    }

                in.close();
                out.close();
    }       
}
Was it helpful?

Solution

Your CharCounter is always 0, and your comparison is incorrect, try something like this:

import java.io.*;

public class TextFile {
    public static void main (String[] args) throws IOException {
        File file1 = new File("intext.txt");
        File file2 = new File("outtext.txt"); 
        char CharCounter = 0;       
        BufferedReader in = (new BufferedReader(newFileReader(file1)));
        PrintWriter out = (new PrintWriter(new FileWriter(file2)));
        int ch;
        while ((ch = in.read()) != -1){
            if (Character.isUpperCase(ch)){
                Character.toLowerCase(ch);

            }
            out.write(ch);
        }
        in.close();
        out.close();
    }       
}

OTHER TIPS

There are a couple of problems in your script:

  • you need to capture the result of Character.toLowercase - it returns the given char in lowercase, it does not modify the supplied char
  • you will only be writing the uppercase chars as it stands

How about this:

File file1 = new File("intext.txt");
File file2 = new File("outtext.txt");
BufferedReader in = (new BufferedReader(new FileReader(file1)));
PrintWriter out = (new PrintWriter(new FileWriter(file2)));

int ch;
while ((ch = in.read()) != -1) {
    if (Character.isUpperCase(ch)) {
        ch = Character.toLowerCase(ch);
    }
    out.write(ch);
}

in.close();
out.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top