如何从txt更改多行

时间:2017-08-18 14:27:00

标签: java

我有一个带有字母的文本文件,我想把它们写成低位字母。这是代码,但它只是最后一行

    BufferedReader in = new BufferedReader(new FileReader("C:\Users\xxx\Desktop\j.txt"));

         String line;
         while((line = in.readLine()) != null)
         {
            blig=line.toUpperCase();
          }     

     try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\xxx\Desktop\j.txt"))) {
         writer.write(blig);
     }

4 个答案:

答案 0 :(得分:0)

您正在浏览整个文件,但只存储最后一行。为了获得所有行,您需要存储您正在读取的所有行,将它们转换为大写,然后将它们写回文件:

List<String> upper = new ArrayList<>();
try(BufferedReader in = new BufferedReader(new FileReader("C:\Users\xxx\Desktop\j.txt")))
{
    String line;
    while((line = in.readLine()) != null)
    {
        // upper.add(line.toUpperCase()); // if you need upper case
        upper.add(line.toLowerCase());    // if you need lower case
    }     
}

try(BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\xxx\Desktop\j.txt")))
{
    for(String str : upper) 
    {
        writer.write(str);
        writer.newLine(); // remove if not needed.
    }
 }

答案 1 :(得分:0)

因为您在没有连接所有结果时只写了最后一行。 用

替换while语句
 blig += line.toUpperCase() + "\\n";

答案 2 :(得分:0)

BufferedReader in = new BufferedReader(new FileReader("C:\Users\xxx\Desktop\j.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\xxx\Desktop\lowerJ.txt"));

String line;
while((line = in.readLine()) != null) {
    writer.write(line.toLowerCase());
}     

答案 3 :(得分:0)

如果你试图降低字符的大小写,那么为什么要使用Uper?

blig=line.toUpperCase();

它应该是bling = line.toLowerCase();