This article contains some code snippets that I commonly use for Java I/O.

Create temp file

Create a temp file inside a specified folder

/** max index reached with temp files */
public static int MAX_INDEX = 100;

/**
 * Create a temporary file in specified folder. To create the file
 * use prefix and postfix passed as parameters. Temporary files
 * are numbered according to an internal index.
 *
 * @param baseDir path of base directory that will contain file
 * @param prefix file prefix
 * @param postfix file postfix
 * @return temporary File or null
 */
public static File createTempFile(String baseDir, String prefix,
		String postfix) throws Exception {
	File parentDir = new File(baseDir);
	File tempFile = null;
	if (parentDir != null) {
		for (int index = 0; index < MAX_INDEX; index++) {
			tempFile = new File(parentDir, prefix + "_" + index + postfix);
			if (!tempFile.exists()) {
				if (tempFile.createNewFile())
					return tempFile;
			}
		}
	}
	return null;
}

Write String to File

Write String content inside a specified file.

public static void writeToFile(String content, File outFile) {
	try {
		// Create file
		FileWriter fstream = new FileWriter( outFile );
		BufferedWriter out = new BufferedWriter(fstream);
		out.write( content );
		// Close the output stream
		out.close();
	} catch (Exception e) {
		// Catch exception if any
		System.err.println("Error: " + e.getMessage());
	}

}

Read String from File, by Filesystem

Read Textual content of a file starting from file path, given on filesystem. The method raises exceptions

public static String tryReadFromFile(String filepath) throws Exception {
	// leggo risorsa da stream
	InputStream inStream = new FileInputStream(filepath);
	byte[] content = new byte[inStream.available()];
	inStream.read(content);
	inStream.close();
	// l'array di byte diventa stringa
	return new String(content);
}

Lettura String da File, tramite Classpath

Read textual content of a file starting from file path, given on classpath. The method raises exceptions

public static String tryReadFromResource(String classpath)
		throws Exception {
	// leggo risorsa da stream
	InputStream inStream = CLASSLOADER.getResourceAsStream(classpath);
	byte[] content = new byte[inStream.available()];
	inStream.read(content);
	inStream.close();
	// l'array di byte diventa stringa
	return new String(content);
}

Lettura String da File, tramite URL

Read textual content from a resource referenced by an URL, given as parameter. The methos raises exceptions

public static String tryReadFromURL(String urlString) throws Exception {
	// lettura risorsa
	URL url = new URL(urlString);
	InputStream inStream = url.openStream();
	byte[] content = new byte[inStream.available()];
	inStream.read(content);
	inStream.close();
	// l'array di byte diventa stringa
	return new String(content);
}

.

.