读取文本文件,然后将大写转换为小写并写入文本文件

时间:2013-11-19 12:17:18

标签: if-statement while-loop bufferedreader uppercase printwriter

我正在尝试读取一个文件,然后写出一个新文件,然后输入文本文件中的大写字符在新输出文件中更改为小写。 该文件将在没有if循环的情况下进行读写,然后当我尝试实现if循环以改变大小写时输出文件打印为空白。任何帮助将不胜感激。

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

2 个答案:

答案 0 :(得分:1)

您的CharCounter始终为0,并且您的比较不正确,请尝试以下操作:

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

答案 1 :(得分:0)

您的脚本中存在一些问题:

  • 你需要捕获Character.toLowercase的结果 - 它以小写形式返回给定的char,它不会修改提供的char
  • 你只会按原样编写大写字符

这个怎么样:

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