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]);
}
}
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.
Regards
Don’t forget to close BufferedWriter and BufferedReader when you don’t need them anymore:
From The Java Tutorials:
With
close()call you implicitly tell it to flush the buffer and close it…