In Java, is there a way to write a file without importing a class (e.g java.io)
No, there is not. In Java, an import
statement is not more than a shortcut for the Java Compiler to resolve unqualified names like String
or Runtime
so that you do not need to fully qualify all the names in the source code - after the compilation is done, in the .class
file, there are only fully qualified references which include the package name.
Even your example
Runtime.getRuntime().exec("echo 'test' > test.txt ")
will become
java.lang.Runtime.getRuntime().exec("echo 'test' > test.txt ")
in the .class
file:
$ javap -c Sample.class
...
public static void main(java.lang.String[]) throws java.io.IOException;
Code:
0: invokestatic #19 // Method java/lang/Runtime.getRuntime:()Ljava/lang/Runtime;
3: ldc #25 // String echo 'test' > test.txt
5: invokevirtual #27 // Method java/lang/Runtime.exec:(Ljava/lang/String;)Ljava/lang/Process;
8: pop
9: return
See also How java import works.