x3lq x3lq - 6 days ago 4
Java Question

Copying file content into a new file deleting old file, renaming new one to old file

I want to open a .java text file and insert a new package name at the top of the file. After some research to this I found out that I have to create a new file insert the new Package name and copy everything from my old file. So far so good.

1) 1st Problem either I am not doing it correct, but how am I able to copy line endings in the correct way? I kinda have the feeling that by copying I lose them, not sure but that since I was more focused on my other Problem

2) The file I am trying to rename just doesn't get renamed, therefore resulting in the problem, that all files in which I want to insert the new package are getting named the same and therefore I am left with the last file with the wrong name. Resulting in a loss of all my other files

private static String insertPackage(File file) throws IOException {
//creating package name
File parent = new File(file.getParent());
String packageName = "package " + parent.getName() + ";\n";

//copy old file
File buffer = new File(parent.getPath()+"\\buffer.java");

Charset charset = Charset.forName("UTF-8");
BufferedReader br = Files.newBufferedReader(file.toPath(),charset);
BufferedWriter bw = Files.newBufferedWriter(buffer.toPath(),charset);

bw.write(packageName,0,packageName.length());

String line;
while((line = br.readLine()) != null){
if(!line.startsWith("package ")) {
bw.write(line, 0, line.length());
}
}

//rename new file
// String filepath = file.getPath();

// File rename = new File(filepath);
boolean renamed = true;
if(file.delete()) {
renamed = buffer.renameTo(file);
}

bw.flush();
bw.close();
br.close();

if(!renamed){
return file.getPath();
}
return "";
}


The return value is just there to have a name in case something is failing. So right now everything.

This is just the function to insert the package name, delete the old package name and, copy everything else into the new file. After that it should delete the old file and rename the new one.

Answer

You are loosing the line breaks, because readLine strips them, but you never write any out to the file. You will need to add a \n (or \r\n depending on your needs) to every line you write to the new file. You can use BufferedWriter#newLine for writing the platform-dependent line separator.

The new file does not get renamed, because your file streams are still open for both files when you try to rename it. Moreover File#renameTo is highly platform dependent (as noted in the documentation) and might not be able to overwrite existing files, I recommend you switch over to Files#move, where you can specify StandardCopyOption.REPLACE_EXISTING.

I can also recommend to fully switch over to the NIO API and not use java.io.File at all, instead use Path directly

Note also that it is a good choice to use try-with-resources instead of manually closing streams, especially when dealing with multiple streams at once.