Java util list file

How to read a text file into ArrayList in Java? Examples

Prior to Java 7, reading a text file into an ArrayList involves a lot of boilerplate coding, as you need to read the file line by line and insert each line into an ArrayList , but from Java 7 onward, you can use the utility method Files.readAllLines() to read all lines of a text file into a List. This method returns a List of String that contains all lines of files. Later you can convert this List to ArrayList, LinkedList, or whatever list you want to. Btw, this the fourth article in the series of reading a text file in Java.

In the earlier parts, you have learned how to read a file using Scanner and BufferedReader (1) . Then, reading the whole file as String (2) and finally reading a text file into an array (3 ). This program is not very different from those in terms of fundamentals.

We are still going to use the read() method for Java 6 solution and will read all text until this method returns -1 which signals the end of the file.

Reading text file into ArrayList in Java — BufferedReader Example

If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in the following example:

BufferedReader bufReader = new BufferedReader(new FileReader("file.txt")); ArrayListString> listOfLines = new ArrayList<>(); String line = bufReader.readLine(); while (line != null) < listOfLines.add(line); line = bufReader.readLine(); > bufReader.close();

Just remember to close the BufferedReader once you are done to prevent resource leak, as you don’t have a try-with-resource statement in Java 6.

Reading text file into List in Java — Files.readAllLines Example

In Java 7, you don’t need to write code to read and store into ArrayList , just call the Files.readAllLines() method and this will return you a list of String, where each element is the corresponding line from the line. Since List is an ordered collection the order of lines in a file is preserved in the list. You can later convert this List to ArrayList or any other implementation.

Читайте также:  Python открыть файл командная строка

here is sample code to read text file into List in JDK 7:

public static ListString> readFileIntoList(String file) < ListString> lines = Collections.emptyList(); try < lines = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); > return lines; >

The readAllLines() method accepts a CharSet , you can use a pre-defined character set e.g. StandardCharsets.UTF_8 or StandardCharsets.UTF_16 . You can also see these free Java Courses to learn more about new file utility classes introduced in Java 7 and 8.

Java Program to read text file into ArrayList

Here is the complete Java program to demonstrate both methods to read a text file into ArrayList. This program first teaches you how to do this in JDK 7 or Java 8 using the Files.readAllLines() method and later using BufferedReader and ArrayList in Java 6 and lower version.

You can compile and run this program from the command prompt or if you want to run in Eclipse, just copy and paste in Eclipse Java project. The Eclipse IDE will automatically create a source file for you.

Then just right-click and Run as Java Program. Make sure you have file.txt in your classpath. Since I have given the relative path here, make sure you put that file inside the Eclipse project directory.

How to read text file into List in Java - example

Reading text file into ArrayList in Java

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* * Java Program read a text file into ArrayList in Java 6 * and Java 8. */ public class ReadFileIntoArrayList < public static void main(String[] args) throws Exception < // reading text file into List in Java 7 ListString> lines = Collections.emptyList(); try < lines = Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); > System.out.println("Content of List:"); System.out.println(lines); // reading text file into ArrayList in Java 6 BufferedReader bufReader = new BufferedReader(new FileReader("file.txt")); ArrayListString> listOfLines = new ArrayList<>(); String line = bufReader.readLine(); while (line != null) < listOfLines.add(line); line = bufReader.readLine(); > bufReader.close(); System.out.println("Content of ArrayLiList:"); System.out.println(listOfLines); > > Output Content of List: [Python, Ruby, JavaScript] Content of ArrayLiList: [Python, Ruby, JavaScript]

That’s all about how to read a text file into ArrayList in Java. You can see it’s very easy in Java 7 and Java 8 by using Files.readAllLines() method. Though you should be mindful of character encoding while reading a text file in Java.

In Java 6 also, the solution using BufferedReader or Scanner is not very difficult to implement, but the thing you need to remember is that you are loading the whole file into memory.

If the file is too big and you don’t have enough memory, your program will die by throwing java.lang.OutOfMemoryError: Java Heap Space . In short, this solution is only good for a small files, for the large files you should always read by streaming.

Источник

Java – How to list all files in a directory?

Two Java examples to show you how to list files in a directory :

1. Files.walk

 try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)
 try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.filter(Files::isDirectory) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)

1.3 List all files end with .java

 try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.map(x -> x.toString()) .filter(f -> f.endsWith(".java")).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)

1.4 Find a file – HeaderAnalyzer.java

 try (Stream walk = Files.walk(Paths.get("C:\\projects"))) < Listresult = walk.map(x -> x.toString()) .filter(f -> f.contains("HeaderAnalyzer.java")) .collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e)

2. Classic

In the old days, we can create a recursive loop to implement the search file function like this :

Читайте также:  Ввод числа

2.1 List all files end with .java

 package com.mkyong.example; import java.io.File; import java.util.ArrayList; import java.util.List; public class JavaExample < public static void main(String[] args) < final File folder = new File("C:\\projects"); Listresult = new ArrayList<>(); search(".*\\.java", folder, result); for (String s : result) < System.out.println(s); >> public static void search(final String pattern, final File folder, List result) < for (final File f : folder.listFiles()) < if (f.isDirectory()) < search(pattern, f, result); >if (f.isFile()) < if (f.getName().matches(pattern)) < result.add(f.getAbsolutePath()); >> > > > 

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Источник

Get list of files and sub-directories in a directory in Java

In this Java tutorial, you will learn how to get the list of files and sub-directories in a given folder, with examples.

Java – Filter files or sub-directories in a directory

You can get the list of files and sub-directories in a given folder using Java. We can also filter the list based on extension or a specific condition.

In this Java Tutorial, we shall learn how to perform the following tasks.

  • Extract list of files and directories in a folder using java
  • Extract list of files belonging to specific file type
  • Extract list of files belonging to specific file type, present in the folder and its sub folders/directories

Extract list of files and sub-directories in a directory

Follow these steps to extract the names of files and sub directories in a given directory.

Step 1 : Specify the folder. In this example, “sample” is the folder name placed at the root to the project.

File folder = new File("sample");

Step 2 : Get the list of all items in the folder.

File[] listOfFiles = folder.listFiles();

Step 3 : Check if an item in the folder is a file.

Step 4 : Check if an item in the folder is a directory.

Complete program that lists the files and directories in a folder is given below.

ListOfFilesExample.java

import java.io.File; import java.util.ArrayList; import java.util.List; /** * Program that gives list of files or directories in a folder using Java */ public class ListOfFilesExample < public static void main(String[] args) < List files = new ArrayList<>(); List directories = new ArrayList<>(); File folder = new File("sample"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < files.add(listOfFiles[i].getName()); >else if (listOfFiles[i].isDirectory()) < directories.add(listOfFiles[i].getName()); >> System.out.println("List of files :\n---------------"); for(String fName: files) System.out.println(fName); System.out.println("\nList of directories :\n---------------------"); for(String dName: directories) System.out.println(dName); > >

The sample folder and its contents are as shown in the below picture :

list of files or directories in a foder using Java - Java Tutorial - tutorialkart.com

When the program is run, output to the console would be as shown below.

List of files : --------------- html_file_1.html text_file_1.txt text_file_3.txt text_file_2.txt List of directories : --------------------- directory_1 directory_2

Get list of files of specific extension from the directory

Step 1 : Specify the folder.

File folder = new File("sample");

Step 2 : Get the list of all items in the folder.

File[] listOfFiles = folder.listFiles();

Step 3 : Check if an item in the folder is a file.

Читайте также:  Check python regex online

Step 4 : Check if the file belong to specified file-type.

Check the extension of the filename with String.endsWith(suffix)

listOfFiles[i].getName().endsWith(fileExtension)

Complete program to get the list of files, that belong to a specified extension type is shown below.

ListOfFilesExample.java

import java.io.File; import java.util.ArrayList; import java.util.List; public class ListOfFilesExample < public static void main(String[] args) < List files = new ArrayList<>(); List directories = new ArrayList<>(); String fileExtension = ".txt"; File folder = new File("sample"); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < if(listOfFiles[i].getName().endsWith(fileExtension))< files.add(listOfFiles[i].getName()); >> > System.out.println("List of .txt files :\n--------------------"); for(String fName: files) System.out.println(fName); > >

When the program is run, Output to the console would be as shown below.

List of .txt files : -------------------- text_file_1.txt text_file_3.txt text_file_2.txt

Get list of files with specific extension from the directory and its sub-directories

Step 1 : Specify the folder.

File folder = new File("D:"+File.separator+"Arjun"+File.separator+"sample");

Step 2 : Get the list of all items in the folder.

File[] listOfFiles = folder.listFiles();

Step 3 : Check if an item in the folder is a file.

Step 4 : Check if the file belong to specified file-type.

Check the extension of the filename with String.endsWith(suffix)

listOfFiles[i].getName().endsWith(fileExtension)

Step 5 : Check if an item in the folder is a directory.

Step 6 : Get the list of files (beloging to specific file-type) recursively from all the sub-directories.

The complete program is given below.

FileListExtractor.java

import java.io.File; import java.util.ArrayList; import java.util.List; public class FileListExtractor < List allTextFiles = new ArrayList(); String fileExtension = ".txt"; public static void main(String[] args) < FileListExtractor folderCrawler = new FileListExtractor(); folderCrawler.crawlFold("sample"); System.out.println("All text files in the folder \"sample\" and its sub directories are :\n---------------------------------------------------------------"); for(String textFileName:folderCrawler.allTextFiles)< System.out.println(textFileName); >> public void crawlFold(String path) < File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) < if (listOfFiles[i].isFile()) < if(listOfFiles[i].getName().endsWith(fileExtension))< allTextFiles.add(listOfFiles[i].getName()); >> else if (listOfFiles[i].isDirectory()) < // if a directory is found, crawl the directory to get text files crawlFold(path+File.separator+listOfFiles[i].getName()); >> > >

When the program is run, output to the console is

All text files in the folder "sample" and its sub directories are : --------------------------------------------------------------- text_file_2_1.txt text_file_1_1.txt text_file_2_1.txt text_file_1_1.txt text_file_2_2.txt text_file_1_2.txt text_file_1.txt text_file_3.txt text_file_2.txt

Conclusion

In this Java Tutorial, we learned how to list all the files and sub-directories in a given folder.

Источник

Java File listFiles(FileFilter filter) method with examples

The listFiles(FileFilter filter) method returns an array of File objects that represent the files and directories that satisfy specified FileFilter .

2. Method signature

public File[] listFiles(FileFilter filter) 

Parameters:

Returns

  • File [] — an array of File objects that represent files and directories that satisfy the specified filter.

Throws

3. Examples

3.1. Code snippet that prints only files (!file.isDirectory()) with the .txt extension (file.getName().endsWith(«.txt»))

package com.frontbackend.java.io; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.util.Arrays; public class FrontBackend < public static void main(String args[]) < try < File tmp = new File("/tmp/ttt"); FileFilter fileFilter = file ->!file.isDirectory() && file.getName() .endsWith(".txt"); File[] list = tmp.listFiles(fileFilter); if (list != null) < Arrays.stream(list) .forEach(file ->< System.out.println(file.getPath() + " " + (file.isDirectory() ? "dir" : "file")); >); > > catch (Exception e) < e.printStackTrace(); >> > 
/tmp/ttt/dest.txt file /tmp/ttt/test.txt file 

4. Conclusion

In this article, we presented the listFiles(FileFilter filter) method that could be used to filter files and directories from the specified path in the filesystem using FileFilter object.

Источник

Оцените статью