0
# File and Package Management
1
2
Core functionality for creating and writing Java source files with proper package structure, import management, and output formatting.
3
4
## Capabilities
5
6
### JavaFile
7
8
Represents a complete Java source file containing a single top-level class, interface, enum, or annotation. Handles package declarations, imports, file comments, and proper Java source formatting.
9
10
```java { .api }
11
/**
12
* A Java file containing a single top level class.
13
*/
14
public final class JavaFile {
15
// Public fields
16
public final CodeBlock fileComment;
17
public final String packageName;
18
public final TypeSpec typeSpec;
19
public final boolean skipJavaLangImports;
20
21
// Static factory method
22
public static Builder builder(String packageName, TypeSpec typeSpec);
23
24
// Writing methods
25
public void writeTo(Appendable out) throws IOException;
26
public void writeTo(Path directory) throws IOException;
27
public void writeTo(Path directory, Charset charset) throws IOException;
28
public Path writeToPath(Path directory) throws IOException;
29
public Path writeToPath(Path directory, Charset charset) throws IOException;
30
public void writeTo(File directory) throws IOException;
31
public File writeToFile(File directory) throws IOException;
32
public void writeTo(Filer filer) throws IOException;
33
34
// Conversion methods
35
public JavaFileObject toJavaFileObject();
36
public Builder toBuilder();
37
38
// Standard object methods
39
public boolean equals(Object o);
40
public int hashCode();
41
public String toString();
42
}
43
```
44
45
**Usage Examples:**
46
47
```java
48
import com.squareup.javapoet.*;
49
import javax.lang.model.element.Modifier;
50
51
// Create a simple class
52
TypeSpec myClass = TypeSpec.classBuilder("MyClass")
53
.addModifiers(Modifier.PUBLIC)
54
.build();
55
56
// Create Java file
57
JavaFile javaFile = JavaFile.builder("com.example", myClass)
58
.addFileComment("Generated code - do not modify")
59
.build();
60
61
// Write to string
62
String sourceCode = javaFile.toString();
63
64
// Write to file system
65
javaFile.writeTo(Paths.get("src/main/java"));
66
67
// Write to annotation processing Filer
68
javaFile.writeTo(processingEnv.getFiler());
69
```
70
71
### JavaFile.Builder
72
73
Builder for configuring JavaFile instances with file comments, static imports, and formatting options.
74
75
```java { .api }
76
public static final class Builder {
77
// Static import management
78
public Builder addStaticImport(Enum<?> constant);
79
public Builder addStaticImport(Class<?> clazz, String... names);
80
public Builder addStaticImport(ClassName className, String... names);
81
82
// File configuration
83
public Builder addFileComment(String format, Object... args);
84
public Builder skipJavaLangImports(boolean skipJavaLangImports);
85
public Builder indent(String indent);
86
87
// Build method
88
public JavaFile build();
89
}
90
```
91
92
**Usage Examples:**
93
94
```java
95
// Configure file with static imports and comments
96
JavaFile javaFile = JavaFile.builder("com.example", typeSpec)
97
.addFileComment("Auto-generated on $L", new Date())
98
.addStaticImport(Collections.class, "emptyList", "singletonList")
99
.addStaticImport(Assert.class, "*")
100
.skipJavaLangImports(true)
101
.indent(" ") // 4 spaces instead of default 2
102
.build();
103
104
// Static import for enum constants
105
JavaFile builderFile = JavaFile.builder("com.example", builderClass)
106
.addStaticImport(Modifier.PUBLIC)
107
.addStaticImport(Modifier.STATIC)
108
.build();
109
```
110
111
### File Writing Options
112
113
JavaFile provides multiple output methods for different use cases:
114
115
#### Console Output
116
```java
117
// Write to System.out
118
javaFile.writeTo(System.out);
119
120
// Write to any Appendable
121
StringBuilder buffer = new StringBuilder();
122
javaFile.writeTo(buffer);
123
```
124
125
#### File System Output
126
```java
127
// Write to directory using standard Java package structure
128
javaFile.writeTo(Paths.get("src/main/java"));
129
130
// Write with specific charset
131
javaFile.writeTo(Paths.get("src/main/java"), StandardCharsets.UTF_8);
132
133
// Write and get the actual output path
134
Path outputPath = javaFile.writeToPath(Paths.get("src/main/java"));
135
System.out.println("Wrote to: " + outputPath);
136
137
// Legacy File API
138
javaFile.writeTo(new File("src/main/java"));
139
File outputFile = javaFile.writeToFile(new File("src/main/java"));
140
```
141
142
#### Annotation Processing Output
143
```java
144
// Write using javax.annotation.processing.Filer
145
@Override
146
public boolean process(Set<? extends TypeElement> annotations,
147
RoundEnvironment roundEnv) {
148
try {
149
javaFile.writeTo(processingEnv.getFiler());
150
} catch (IOException e) {
151
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
152
"Failed to write generated file: " + e.getMessage());
153
}
154
return true;
155
}
156
```
157
158
#### JavaFileObject Integration
159
```java
160
// Convert to JavaFileObject for compiler integration
161
JavaFileObject fileObject = javaFile.toJavaFileObject();
162
163
// Use with JavaCompiler
164
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
165
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
166
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(fileObject);
167
compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
168
```
169
170
### Import Management
171
172
JavaPoet automatically manages imports based on type references in the generated code:
173
174
```java
175
// Types are automatically imported
176
MethodSpec method = MethodSpec.methodBuilder("process")
177
.addParameter(List.class, "items")
178
.addParameter(Map.class, "config")
179
.returns(Optional.class)
180
.addStatement("$T result = new $T<>()", ArrayList.class, ArrayList.class)
181
.addStatement("return $T.of(result)", Optional.class)
182
.build();
183
184
// Generated imports:
185
// import java.util.List;
186
// import java.util.Map;
187
// import java.util.Optional;
188
// import java.util.ArrayList;
189
```
190
191
#### Static Import Control
192
```java
193
// Add static imports for cleaner code
194
JavaFile.builder("com.example", typeSpec)
195
.addStaticImport(Collections.class, "emptyList")
196
.addStaticImport(Assertions.class, "*")
197
.build();
198
199
// Results in:
200
// import static java.util.Collections.emptyList;
201
// import static org.junit.jupiter.api.Assertions.*;
202
```
203
204
#### java.lang Import Control
205
```java
206
// Skip java.lang imports (default behavior includes them)
207
JavaFile.builder("com.example", typeSpec)
208
.skipJavaLangImports(true)
209
.build();
210
211
// Without skipJavaLangImports: import java.lang.String;
212
// With skipJavaLangImports: String used without import
213
```
214
215
### File Comments and Documentation
216
217
```java
218
// Add file-level comments
219
JavaFile.builder("com.example", typeSpec)
220
.addFileComment("This file was auto-generated on $L", Instant.now())
221
.addFileComment("")
222
.addFileComment("Copyright (c) $L Example Corp", Year.now().getValue())
223
.addFileComment("All rights reserved.")
224
.build();
225
226
// Generates:
227
/*
228
* This file was auto-generated on 2023-10-15T14:30:00Z
229
*
230
* Copyright (c) 2023 Example Corp
231
* All rights reserved.
232
*/
233
```