forked from jbloch/effective-java-3e-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppPackage.java
More file actions
70 lines (59 loc) · 2.21 KB
/
Copy pathAppPackage.java
File metadata and controls
70 lines (59 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class AppPackage {
public static void main(String[] args) {
try {
String path = "/Users/deepakcdo/Documents/MySpace/Dev/corejava/src/main/java/";
walk((path));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void walk(String path) {
File root = new File(path);
File[] list = root.listFiles();
if (list == null) return;
for (File f : list) {
if (f.isDirectory()) {
walk(f.getAbsolutePath());
System.out.println("Dir:" + f.getAbsoluteFile());
} else {
if (f.getName().endsWith(".java")) {
addPackageToClass(f.getAbsolutePath());
}
}
}
}
private static void addPackageToClass(String file) {
try {
List<String> strings = Files.readAllLines(
Paths.get(file));
String packageName = getPackageName(file);
String firstLine = strings.get(0);
replaceKeyWord("package", strings, firstLine, packageName);
// replaceKeyWord("module", strings, firstLine, packageName);
Files.write(Paths.get(file), strings);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void replaceKeyWord(String keyWord, List<String> strings, String firstLine, String packageName){
if (firstLine.startsWith(keyWord) ){
strings.remove(0);
strings.add(0, keyWord + " " + packageName + ";" + System.lineSeparator());
}
}
private static String getPackageName(String fileName) {
String removeSufix = fileName.replace("/Users/deepakcdo/Documents/MySpace/Dev/corejava/src/main/java/", "");
String[] split = removeSufix.split("/");
String returnValue = "";
for (int i = 0; i < (split.length - 1); i++) {
returnValue = returnValue + split[i] + ".";
}
returnValue = returnValue.substring(0, returnValue.length() - 1);
return returnValue;
}
}