Sams Teach Yourself Java in 24 Hours Sixth Edition by Rogers Cadenhead Chapter 20 ConfigWriter.java error
I am a Java beginner. I am going through the Java book listed in the title of this post. I am super stumped at how this cannot work. The code is supposed to create a file called program.properties and put the text in lines 10 through 12 in it.
import java.io.*;
class ConfigWriter {
String newline = System.getProperty("line.separator");
ConfigWriter() {
try {
File file = new File("program.properties");
FileOutputStream fileStream = new FileOutputStream(file);
write(fileStream, "username=max");
write(fileStream, "score=12550");
write(fileStream, "level=5");
} catch (IOException ioe) {
System.out.println("Could not write file");
}
}
void write(FileOutputStream stream, String output)
throws IOException {
output = output + newline;
byte[] data = output.getBytes();
stream.write(data, 0, data.length);
}
public static void main(String[] arguments) {
ConfigWriter cw = new ConfigWriter();
}
}
Instead it does absolutely nothing. Its completely blank. I would most appreciate any help at all with this error!
The most likely problem is that you are confused about where the file will be written.
If you write to a file using a relative pathname (like “program.properties”), Java will attempt to open / create the file in the application’s “current directory”.
If you run the code directly from the command prompt / shell, the current directory will be the shell’s current directory … at the point that you ran the program.
If you launch using a wrapper script, then the script could change the current directory before starting the program.
If you launch from an IDE, then the IDE determines what the current directory will be.
And so on.
To avoid this problem, use an absolute pathname.
It would also be instructive to figure out where that file was actually written. On Windows you could try using the Search tool. On Linux, the
findcommand is a good choice; e.g.… and wait.
Note that flushing and closing are not necessary in this particular example. You are using a
FileOutputStreamwhich is not buffered. However, if you wanted to do that, your code would need to look like this:Note that the
fileStreamis implicitly closed because we declared it as a “resource” following thetry