简体   繁体   中英

Java code to copy all the text while converting upper case letters from one text file to lower case letters in another text file

I am having problem with the code that I wrote to convert upper case letters from one file to lower case letters in another. When the code is run for some text file named inputtext.txt it creates the output file but the upper case text aren't being converted.

import java.io.*;

public class TextFile {
    public static void main (String[] args) throws IOException {
    // Assume default encoding.
         // The name of the file to open for reading.
            File filein = new File("inputtext.txt");
         // The name of the file to open for writing.
            File fileout = new File("outputtext.txt"); 
            char CharCounter = 0;       
            BufferedReader in = (new BufferedReader(new FileReader(filein)));
            PrintWriter out = (new PrintWriter(new FileWriter(fileout)));

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

                if (Character.isUpperCase(z)){
                    Character.toLowerCase(z);

                }
                out.write(z);


            }
            // Always close files.
            in.close();
            out.close();
        }       
    }

You can read line by line and then covert to lower case while writing.

    BufferedReader br = new BufferedReader(new FileReader(new File("a")));
    PrintWriter pw = new PrintWriter(new FileWriter(new File("b")));
    String line = null;
    while((line = br.readLine()) != null){
        pw.write(line.toLowerCase());
    }
    pw.close();
    br.close();

Your code is fine. Problem is Character.toLowerCase(z) DOES NOT CONVERT THE VALUE OF z , rather returns you a new value, which is the lower case of the variable z

int theLowerCaseOfZ = Character.toLowerCase(z);

And you could easily kill your problem by this

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

                if (Character.isUpperCase(z)){ 
                    // SMOKING GUN!!!
                    out.write( (int) Character.toLowerCase(z) );

                }

            }
            // Always close files.
            in.close();
            out.close()

And you could also do

int theLowerCaseOfZ = (int) Character.toLowerCase(z);
out.write(theLowerCaseOfZ);

With all love RANA SAHIB :) , Rachit's answer is useful too, and I am open to further clarification if needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM