About three times a year I have to accomplish the seemingly easy task of reading the contents of a file into a String. Apparently the Sun folks did not find it necessary to create an API for this. So this piece of obscure code is the best I can come up with. There should be a more elegant way to do this.
private String readFile(String fileName) { File file = new File(fileName); char[] buffer = null; try { BufferedReader bufferedReader = new BufferedReader( new FileReader(file)); buffer = new char[(int)file.length()]; int i = 0; int c = bufferedReader.read(); while (c != -1) { buffer[i++] = (char)c; c = bufferedReader.read(); } } catch (FileNotFoundException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } return new String(buffer); }
Labels
(None)