Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Saturday, May 25, 2013

Handling files in Java

The java.io.File class provides ways to access file and directory information. It also allows file-level operations like rename, delete and move.

Checkout the source here.

/**
 * A program to list all files and directories in a given directory.
 *
 * @author megha birmiwal
 */
public class DirectoryLister {

        public void listDirectories(String filepath) {

                File topDir = new File(filepath);
                if (!topDir.exists()) {
                        System.out.println("Directory does not exist: " + filepath);
                        return;
                }

                if (!topDir.isDirectory()) {
                        System.out.println("Not a directory: " + filepath);
                        return;
                }

                File[] files = topDir.listFiles();

                for (File file : files) {
                        if (file.isHidden()) {
                                // do not show hidden files
                                continue;
                        }
                        if (file.isDirectory()) {
                                System.out.println(file.getName() + " - D");
                        } else {
                                System.out.println(file.getName() + " - " + file.length());
                        }
// You can use the File APIs to play around with files, eg. rename or delete etc.
//                      String name = file.getName();
//                      name = name.replace(".png", ".jpg");
//                      name = name + ".txt";
//                  file.renameTo(new File(name));
//          file.delete();
                }
        }

        public static void main(String[] args) {
                DirectoryLister lister = new DirectoryLister();
                lister.listDirectories("/");
        }
}

Monday, November 5, 2012

File IO

An example of how to read/write text files in java.
http://code.google.com/p/java-through-examples/source/browse/src/org/megha/blog/example/io/#io

package org.megha.blog.example.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * Reads all lines from a {@link Reader}.
 * Don't use this to read huge files!
 *
 * @author megha birmiwal
 */
public class LinesReader {

        private Reader reader;
       
        public LinesReader(Reader reader) {
                this.reader = reader;
        }

        /**
         * Reads all the lines from the provided {@link Reader}.
         *
         * @return a list of strings (lines from the file)
         * @throws IOException if there was an exception reading from the file
         */
        public List<String> readAllLines() throws IOException {
                BufferedReader bufferedReader = new BufferedReader(reader);
                List<String> lines = new ArrayList<String>();
                String line = bufferedReader.readLine();
                while (line != null) {
                        lines.add(line);
                        line = bufferedReader.readLine();
                }
                return lines;
        }
}
package org.megha.blog.example.io;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Reads a file and writes unique words as output into another.
 *
 * @author megha birmiwal
 */
public class UniqueWords {

        public static void main(String args[]) throws IOException {
                if (args.length != 2) {
                        System.out.println("please provide two file names: <infile> <outfile>");
                        return;
                }
               
                FileReader fileReader = null;
                try {
                        fileReader = new FileReader(args[0]);
                } catch (FileNotFoundException e) {
                        System.out.println("file not found: " + e.getMessage());
                        return;
                }
                LinesReader lineReader = new LinesReader(fileReader);
                List<String> readLines = null;
                try {
                        readLines = lineReader.readAllLines();
                } catch (IOException e) {
                        System.out.println("IOException while reading from file: " + e.getMessage());
                        return;
                } finally {
                        fileReader.close();
                }
                // Prints all the lines in the file
//              for (String line : readLines) {
//                      System.out.println(line);
//              }

                // Get all the unique words and save in a file
                Set<String> uniquewords = new HashSet<String>();
                for (String line : readLines) {
                        String[] words = line.split("[ ;,/\\(\\)\\[\\]\"\\t]");
                        for(String word : words) {
                                uniquewords.add(word);
                        }
                }

                Writer writer = new FileWriter(args[1]);
                try {
                        for(String word : uniquewords) {
        //                      System.out.println(word);
                                writer.write(word + "\n");
                        }
                } finally {
                        writer.close();
                }
        }
}