Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read directories in java

simple: how do i read the contents of a directory in Java, and save that data in an array or variable of some sort? secondly, how do i open an external file in Java?

like image 624
NoodleOfDeath Avatar asked Apr 30 '11 12:04

NoodleOfDeath


People also ask

How do you handle the directories in Java?

In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false​.

How do I access a directory?

Type cd folderName to open a folder in your directory. For example, in your User folder you can type cd documents and press ↵ Enter to open your Documents folder.

How do you get a list of all files in a folder in Java?

The List() method. This method returns a String array which contains the names of all the files and directories in the path represented by the current (File) object. Using this method, you can just print the names of the files and directories.


2 Answers

You can use java IO API. Specifically java.io.File, java.io.BufferedReader, java.io.BufferedWriter etc.

Assuming by opening you mean opening file for reading. Also for good understanding of Java I/O functionalities check out this link: http://download.oracle.com/javase/tutorial/essential/io/

Check the below code.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileIO 
{
    public static void main(String[] args) 
    {
        File file = new File("c:/temp/");

        // Reading directory contents
        File[] files = file.listFiles();

        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i]);
        }

        // Reading conetent

        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader("c:/temp/test.txt"));
            String line = null;

            while(true)
            {
                line = reader.readLine();
                if(line == null)
                    break;

                System.out.println(line);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            if(reader != null)
            {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
like image 145
Favonius Avatar answered Oct 04 '22 15:10

Favonius


You can use a class java.io.File to do that. A File is an abstract representation of file and directory pathnames. You can retrieve the list of files/directories within it using the File.list() method.

like image 36
greydet Avatar answered Oct 04 '22 15:10

greydet