Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

file io - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...