Tuesday, July 28, 2009

Java: encoding and listing files in a directory

Two code snippets tested to be working under win32 at least;

Encoding. When your input text files are in encoding different from your default platform's there is no way to use FileReader in this case. Instead you should go deeper in the class hierarchy and specify a file enconding, which you know in advance. Code (inspired by answers here):

private static String loadFileContents(String filename)
throws FileNotFoundException, IOException {
StringBuilder contents = new StringBuilder();

InputStream is =
new BufferedInputStream(new FileInputStream(filename));
Reader reader = new InputStreamReader(is, "UTF8");

BufferedReader bufferedReader =
new BufferedReader(reader);

String line;
while ( (line = bufferedReader.readLine()) != null ) {
contents.append(line + "\n");

return contents.toString();

Directory listing. Suppose you want to list files in a directory based on some filename criteria. Easy way to do this is to implement a custom filename filter. Entire code (watched here):

package org.dk.mt;

import java.io.File;
import java.io.FilenameFilter;

* @author Dmitry_Kan
* Lists given directory based on filename pattern
public class DirectoryLister {

private String filenamePattern;
private String dirname;

public DirectoryLister(String filepat, String directory) {
filenamePattern = filepat;
dirname = directory;

public String[] getListOfFiles() {
class CustomFilter implements FilenameFilter {
public boolean accept(File dir, String s) {
if (s.contains(filenamePattern) && s.contains("txt") )
return true;
return false;
return new java.io.File(dirname).list(new CustomFilter());


No comments: