Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import java.net.URL;

import java.util.Vector;

public class Main {
    /** List of temporary files created in this session */
    private static Vector tempFileList = new Vector();
    /** A temp directory SwingWT can use (not used at present) */
    private static String tempDirectory = System.getProperty("user.home") + File.separator + "tmp" + File.separator
            + "swingwt";

    /**
     * Given a byte array of content, writes it to a temporary file and then
     * returns the path to it as a URL
     * @param contents The content of the file
     * @param type The file extension to use
     * @throws IOException if an error occurs
     */
    public static URL stringToTempFile(byte[] contents, String type) throws IOException {

        // Make sure we have a temp directory
        checkForTempDirectory();

        // Generate a random file name and keep doing it until we get a unique one
        File f = null;
        String fName = null;
        do {
            fName = tempDirectory + File.separator + ((int) (Math.random() * 10000000)) + "." + type;
            f = new File(fName);
        } while (f.exists());

        System.out.println("TEMP: Creating temp file " + fName);
        FileOutputStream out = new FileOutputStream(f);
        out.write(contents);
        out.close();

        // Remember this file for later deletion
        tempFileList.add(fName);

        return new URL("file://" + fName);
    }

    /** Checks to see if this users temp directory is there
     *  and creates it if it isn't. 
     *  @throws IOException if the directory couldn't be created.
     */
    private static void checkForTempDirectory() throws IOException {
        File f = new File(tempDirectory);
        if (!f.exists())
            f.mkdirs();
    }
}