Java: Handling Files (Reading, Writing, Fetching Webpage)

This is a collections of Java methods that are needed all the time, but you forget the code for it anyways because in Java, sometimes things that should be simple one liners are quite blown up (well, if you eg do use the writer/reader classes instead of the streams to write/read a file it is not as bad).

Logging/Writing to a File  
    /**
     * appends the given string to a log file and adds a newline character.
     *
     * @param s string to log
     * @param fileName name of the log file (or path, base path: user home)
     * @param whether or not to prepend the current date and time before s
     */

    public void log(String s, String fileName, boolean prepentDate) {
        String path = System.getProperty("user.home")
                + System.getProperty("file.separator");
        String preString = "";
        if (prepentDate) {
            preString = getDate("yyyy.MM.dd-HH:mm:ss-z") + ": ";
        }

        FileWriter fw = null;
        try {
            fw = new FileWriter(path + fileName, true);
            fw.write(preString + s + "\n");
        } catch (Exception ex) {
            System.out.println(this.getClass().getName()
                    + ".log(): ERROR writing to log:"
                    + path + fileName + ": " + ex);
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException ex) {
                    System.out.println(this.getClass().getName()
                    + ".log(): ERROR closing stream:"
                    + path + fileName + ": " + ex);
                }
            }
        }
    }

    /**
     * returns the current date in desired format.
     *
     * example for format: "yyyy.MM.dd-HH:mm:ss-z" or "yyyy.mm.dd".
     * @param format
     * @return
     */

    public String getDate(String format) {
        DateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(new Date());
    }
An alternative is to use the OutputStreamWriter:
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName));
    try {
      osw.write(message);
    }
    finally {
      osw.close();
    }
  Reading a File  
    public String read(String fileName) throws IOException {
        BufferedReader br = null;
        String content = "";
        try {
            br = new BufferedReader(new FileReader(fileName));
            String read;
            while ((read = br.readLine()) != null) {
                content += read + '\n';
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }
        return content;
    }
  Reading a remote file/a web page  
    /**
     * connects to and retrieves the page.
     * @return html page in string form
     * @throws Exception
     */

    public String getHTML(String url) throws MalformedURLException, IOException {
        String html = "";
        URL myUrl = new URL(url);

        HttpURLConnection httpcon = (HttpURLConnection) myUrl.openConnection();
        httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); // ua needed by some pages, eg google search
        BufferedReader in = null;
        try {
            String line;
            in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
            while ((line = in.readLine()) != null) {
                html = html + line + "\n";
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return html;
    }
 
  If you think that there is a better way of doing some of this or if you know some more code that is often needed but hard to remember please share in the comments section.

Leave a Reply

Your email address will not be published.