Skip to content

Instantly share code, notes, and snippets.

@carchrae
Created November 29, 2012 23:33
Show Gist options
  • Save carchrae/4172659 to your computer and use it in GitHub Desktop.
Save carchrae/4172659 to your computer and use it in GitHub Desktop.
public static void writeStringToFile(final File file, final String data) {
try {
final OutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(file, false));
outputStream.write(data.getBytes("UTF-8"));
outputStream.close();
} catch (IOException e) {
throw new RuntimeException("could not write file for debug cache", e);
}
try {
int start = data.indexOf("package");
if (start != -1) {
int end = data.indexOf(";", start);
String packageName = data.substring(8, end).trim();
// creates a copy of the generated file with the correct package dirs
String packageDirs = packageName.replace(".", "/");
String parentPath = file.getParent();
if (!parentPath.endsWith(packageDirs)) {
// only write it if the original file was not in the right hierarchy
String packagePath = parentPath + "/java/" + packageDirs;
new File(packagePath).mkdirs();
final OutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(packagePath + "/" + file.getName(),
false));
outputStream.write(data.getBytes("UTF-8"));
outputStream.close();
}
}
} catch (IOException e) {
throw new RuntimeException("could not write file for debug cache", e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment