【问题标题】:Copying a file character by character in Java在Java中逐字符复制文件
【发布时间】:2016-04-15 13:48:15
【问题描述】:

我正在做一个练习,我必须在 Java 中逐个字符地复制文件。我正在使用以下文件:

Hamlet.txt
To be, or not to be: that is the question.
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them ?

我创建了第二个文件,名为copy.txt,其中将包含Hamlet.txt 的逐个字符副本问题是,在我运行我的代码后,copy.txt 仍然为空。

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class Combinations {
    public void run() {
        try {
            BufferedReader rd = new BufferedReader(new FileReader("Hamlet.txt"));
        PrintWriter wr = new PrintWriter(new BufferedWriter(new FileWriter("copy.txt")));
        copyFileCharByChar(rd, wr);
    }catch(IOException ex) {
        throw new RuntimeException(ex.toString());
    }
}

private void copyFileCharByChar(BufferedReader rd, PrintWriter wr) {
    try {
        while(true) {
            int ch = rd.read();
            if(ch == - 1) break;
            wr.print(ch);
        }
      } catch(IOException ex) {
        throw new RuntimeException(ex.toString());
    }
    }

public static void main(String[] args) {
    new Combinations().run();
}
}

所以我写了一个方法copyFileCharByChar,它接受一个BufferedReader对象rd和一个FileWriter对象wrrd 读取每个单独的字符,wr 写入相应的字符。我在这里做错了什么?

【问题讨论】:

  • 顺便说一句,为什么new PrintWriter(new BufferedWriter(new FileWriternew BufferedWriter(new FileWriternew FileWriter 就足够了。
  • @ArnaudDenoyelle 每个级别都会提高编写器对象的效率。

标签: java file filereader filewriter


【解决方案1】:

在这种情况下你需要强制打印:

wr.print((char)ch);

或者使用write方法:

wr.write(ch);

您还需要关闭 PrintWriter:

wr.close();

【讨论】:

  • 我不同意第一种说法。它无需转换为 char 即可工作(因为 OP 写入了 rd.read() 的结果,这已经是一个 ascii 代码)。
  • @ArnaudDenoyelle 实际上,如果没有这种情况,它只会打印数字,因为 ch 是一个 int。但是 write 方法不需要强制转换,只有在我调用 print 时才需要。
  • @MutatingAlgorithm 我很遗憾,我在没有演员表的情况下进行了测试,它就像一个魅力。 API 采用和 int ,它是字符的 ASCII 码。因此,为了写1,你可以调用wr.print(0x31)
  • @ArnaudDenoyelle wr.print(int) 打印整数作为文本,不是吗?这是API says 的内容:“打印一个整数。由 String.valueOf(int) 生成的字符串被转换为字节......”
  • @whiskeyspider 看来我们调用的不是同一个方法。在我的 jvm (8) 上,调用的方法(有或没有强制转换)是相同的:PrintWriter#write(int c)docs.oracle.com/javase/8/docs/api/java/io/…
猜你喜欢
  • 2013-08-05
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 2014-04-30
  • 2021-11-26
  • 2011-01-25
  • 2011-06-16
相关资源
最近更新 更多