How to read directories in java

simple: how can I read the contents of a directory in Java and store this data in an array or variable of some kind? secondly, how to open an external file in Java?

+4
source share
4 answers

You can use the java IO API. In particular java.io.File , java.io.BufferedReader , java.io.BufferedWriter , etc.

Assuming that you are opening, you mean the opening file for reading. Also, for a good understanding of Java I / O functionality, check out this link: http://download.oracle.com/javase/tutorial/essential/io/

Check out the code below.

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

You can use the java.io.File class for this. A file is an abstract representation of file names and directories. You can get a list of files / directories inside it using the File.list () method.

+2
source

There is also a Commons IO package that has many methods for managing files and directories.

 import java.io.File; import java.io.IOException; import java.util.Collection; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FileFilterUtils; public class CommonsIO { public static void main( String[] args ) { // Read the contents of a file into a String try { String contents = FileUtils.readFileToString( new File( "/etc/mtab" ) ); } catch (IOException e) { e.printStackTrace(); } // Get a Collection of files in a directory without looking in subdirectories Collection<File> files = FileUtils.listFiles( new File( "/home/ross/tmp" ), FileFilterUtils.trueFileFilter(), null ); for ( File f : files ) { System.out.println( f.getName() ); } } } 
+2
source
 public class StackOverflow { public static void main(String[] sr) throws IOException{ //Read a folder and files in it File f = new File("D:/workspace"); if(!f.exists()) System.out.println("No File/Dir"); if(f.isDirectory()){// a directory! for(File file :f.listFiles()){ System.out.println(file.getName()); } } //Read a file an save content to a StringBuiilder File f1 = new File("D:/workspace/so.txt"); BufferedReader br = new BufferedReader(new FileReader(f1)); StringBuilder sb = new StringBuilder(); String line = ""; while((line=br.readLine())!=null) sb.append(line+"\n"); System.out.println(sb); } } 
+1
source

All Articles