简体   繁体   English

Java代码复制所有文本,同时将大写字母从一个文本文件转换为另一文本文件中的小写字母

[英]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. 当为某些名为inputtext.txt的文本文件运行代码时,它会创建输出文件,但不会转换大写文本。

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 问题是Character.toLowerCase(z)不转换z的值 ,而是返回一个新值,它是变量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 对于所有喜欢RANA SAHIB的人 :), 拉奇(Rachit)的回答也很有用,如果需要,我愿意进一步澄清

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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