繁体   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

我编写的将一个文件中的大写字母转换为另一个文件中的小写字母的代码有问题。 当为某些名为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();
        }       
    }

您可以逐行阅读,然后在写入时将其转换为小写。

    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();

您的代码很好。 问题是Character.toLowerCase(z)不转换z的值 ,而是返回一个新值,它是变量z的小写

int theLowerCaseOfZ = Character.toLowerCase(z);

这样您就可以轻松解决问题

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()

你也可以

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

对于所有喜欢RANA SAHIB的人 :), 拉奇(Rachit)的回答也很有用,如果需要,我愿意进一步澄清

暂无
暂无

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

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