使用java.nio从另一个文件读取后,无法写入文件 [英] Not been able to write to a file, after reading from another file using java.nio

查看:208
本文介绍了使用java.nio从另一个文件读取后,无法写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取一个.java文件,并尝试通过使用以下代码将其写入另一个文件.

I am trying to read one .java file and trying to write it to another file by using the below code.

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

public class JavaToHtml
{
    private Path actualPath;
    private Path targetPath;
    private Path sourcePath;

    private BufferedReader reader;
    private BufferedWriter writer;

    public JavaToHtml(String source, String target)
    {
        sourcePath = Paths.get(source);
        sourcePath = sourcePath.toAbsolutePath();
        actualPath = Paths.get(target);
        targetPath = actualPath.toAbsolutePath();

        Charset charset = Charset.forName("US-ASCII");

        try
        {   
            reader = Files.newBufferedReader(sourcePath, charset);
            writer = Files.newBufferedWriter(targetPath, charset);

            String line = null;
            while((line = reader.readLine()) != null)
            {
                            // This thing is working.
                System.out.println(line);
                            // This thing is not working.
                writer.write(line, 0, line.length());
            }
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new JavaToHtml(args[0], args[1]);
    }
}

现在的问题是,在我的while循环中,我能够读取源文件而没有任何问题,但是创建的新文件(目标)始终为空.而且,无论在编译时还是在运行时,编译器都不会抛出错误.难道我做错了什么 ?请给我一些光线,因为这是我的第一个问题.

Now the thing is, in my while loop i am able to read the source file without any issues but the new file (The target) which is created is always empty. Moreover the compiler throws no errors, neither at Compile Time nor at Run Time. Am i doing something wrong ? Please, show me some light, as this being my first question.

致谢

推荐答案

当您不再需要BufferedWriter和BufferedReader时,不要忘记关闭它们:

Don't forget to close BufferedWriter and BufferedReader when you don't need them anymore:

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

来自 Java教程:

缓冲的输入流从称为缓冲区的存储区中读取数据; 仅当缓冲区为空时,本机输入API才称为 . 同样,缓冲的输出流将数据写入缓冲区,并且 仅在缓冲区已满时才将本机输出API称为 .

Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full.

通过close()调用,您隐式告诉它刷新缓冲区并关闭它...

With close() call you implicitly tell it to flush the buffer and close it...

这篇关于使用java.nio从另一个文件读取后,无法写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆