hoping you're doing well, this is my first question
I have a trouble:
My goal is to create java files from pieces of code (fields, attributes, constructor)
I tried to do this by altering between reading and writing file.
Reading file to get the old value , delete closing "}"
Writing in file : the new piece of code, plus closing "}"
The problem with my try is that Files.readAllLine() or FileWriter() is not working.
You can find my source code below.
public static void fillFile(String fileName, String name, String value) throws IOException {
Path path = Paths.get(fileName);
List<String> all = Files.readAllLines(path,StandardCharsets.UTF_8);
System.out.println(" the path "+Paths.get(fileName));
System.out.println(name + " :; "+ value);
System.out.println("to write " + all.toString().replaceAll(", ", " ").substring(1, (all+"").replaceAll(", ", " ").length()-1) + "\n" + name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n } ddddddddddddddddddddddd");
FileWriter test = new FileWriter(fileName,true);
test.write(all.toString().replaceAll(", ", " ").substring(1, all.toString().replaceAll(", ", " ").length()-1) + "\n" + name + (name.endsWith(")")?"":" = ")+ value+ (name.endsWith(")")?"":";")+"\n }");
//test.flush();
test.close();
}
Another question : there is an other easy way to reach my goal ?
The solution is that the FileWriter
classe should have a different path that the one which File.readAllLine()
use.
So we have to create a temporary file, which will be copied to the desired fileName
file, then we delete the temporary file
Hope this will help people who need it. It is working !!!
public static void fillFile(String fileName, String name, String value) throws IOException {
Path path = Paths.get(fileName);
List<String> all = null;
if (path.toFile().exists()) {
all = Files.readAllLines(path,StandardCharsets.UTF_8);}
if(all!= null) System.out.println(path + " the size of "+ all.toArray(new String[all.size()])+"");
Path path2 = Files.createTempFile(path.getParent(),"test-file", ".java");
Files.write(path2, ((all+"").replaceAll(", ", "\n").replaceAll("\\[", "").replaceAll("\\]", "").substring(1, ((all+"").replaceAll(", ", " ").replaceAll("\\[", "").replaceAll("\\]", "")).length()-1) + "\n" + name + value+ "\n" +"}").getBytes());
Files.copy(path2, path, StandardCopyOption.REPLACE_EXISTING);
Files.deleteIfExists(path2);
}