从文件中读取字符

发布于 2024-09-24 05:23:58 字数 121 浏览 1 评论 0 原文

我想一次读取一个文件一个字符,并将第一个文件的内容一次一个字符写入另一个文件。

我之前也问过这个问题,但没有得到满意的答案...... 我能够读取文件并将其打印到 std o/p。但无法将相同的读取字符写入文件。

i want to read a file one character at a time and write the contents of first file to another file one character at a time.

i have asked this question earlier also but didnt get a satisfactory answer.....
i am able to read the file and print it out to std o/p.but cant write the same read character to a file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

弃爱 2024-10-01 05:23:58

链接到您之前的问题以查看哪些方面不满意可能会很有用。这是一个基本示例:

public static void copy( File src, File dest ) throws IOException {
    Reader reader = new FileReader(src);
    Writer writer = new FileWriter(dest);

    int oneChar = 0;
    while( (oneChar = reader.read()) != -1 ) {
        writer.write(oneChar);
    }

    writer.close();
    reader.close();     
}

需要考虑的其他事项:

  • 使用 BufferedReader/Writer 包装读取器/写入器以获得更好的性能
  • 关闭调用应该位于 finally 块中以防止资源泄漏

It may have been useful to link to your previous question to see what was unsatisfactory. Here's a basic example:

public static void copy( File src, File dest ) throws IOException {
    Reader reader = new FileReader(src);
    Writer writer = new FileWriter(dest);

    int oneChar = 0;
    while( (oneChar = reader.read()) != -1 ) {
        writer.write(oneChar);
    }

    writer.close();
    reader.close();     
}

Additional things to consider:

  • wrap reader/writer with BufferedReader/Writer for better performance
  • the close calls should be in a finally block to prevent resource leaks
梦境 2024-10-01 05:23:58

您可以使用 FileReader (有一个 read 方法,如果您愿意,可以一次执行一个字符),并且您可以使用 FileWriter (有一个字符-一次 write 方法)。还有一些方法可以处理字符块而不是一次处理一个字符,但您似乎想要这些,所以...

如果您不担心设置字符编码,那就太好了。如果是,请查看使用 FileInputStream< /code>FileOutputStream InputStreamReaderOutputStreamWriter 包装器(分别)。 FileInputStreamFileoutputStream 类使用字节,然后流读取器/写入器根据您选择的编码将字节转换为字符。

You can read characters from a file by using a FileReader (there's a read method that lets you do it one character at a time if you like), and you can write characters to a file using a FileWriter (there's a one-character-at-a-time write method). There are also methods to do blocks of characters rather than one character at a time, but you seemed to want those, so...

That's great if you're not worried about setting the character encoding. If you are, look at using FileInputStream and FileOutputStream with InputStreamReader and OutputStreamWriter wrappers (respectively). The FileInputStream and FileoutputStream classes work with bytes, and then the stream reader/writers work with converting bytes to characters according to the encoding you choose.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文