Java файлы во всех папках

Файлы и директории, класс File

Класс File пакета java.io используется для управления информацией о файлах и каталогах. На уровне операционной системы файлы и каталоги имеют существенные отличия, но в Java они описываются одним классом File. Каталог в Java трактуется как обычный файл, но с дополнительным свойством — списком имен файлов, который можно просмотреть с помощью метода list.

В зависимости от назначения объект File — файл или каталог, можно использовать один из конструкторов для создания объекта:

File (String путь_к_каталогу); File (String путь_к_каталогу, String имя_файла); File (File каталог, String имя_файла);

Примеры создания объектов File

// Создание File для каталога File dir = new File("C://dir_test"); // Создание File для файлов, которые находятся в каталоге File file1 = new File("C://dir_test", "Hello1.txt"); File file2 = new File(dir, "Hello2.txt");

Свойства и методы класса File

Для определения стандартных свойств файла в классе File имеются различные методы. Однако класс File несимметричен, т.е. методы определения свойств объекта существуют, но соответствующие функции для изменения этих свойств отсутствуют.

Функции Описание
String getName() Наименование файла или каталога.
String getParent() Наименование родительского каталога.
long length() Функция определения размера файла в байтах.
String getAbsolutePath() Функция определения абсолютного пути файла или каталога.
boolean delete() Удаления файла или каталога.
boolean exists() Проверка существования файла или каталога.
boolean isDirectory() Проверка, является ли данный объект каталогом.
boolean isFile() Проверка, является ли данный объект файлом.
long lastModified() Функция определения даты последней модификации файла.
boolean canRead() Проверка, можно ли читать данные из файла.
boolean canWrite() Проверка, можно ли записывать данные в файл.
boolean isHidden() Проверка, являются ли каталог или файл скрытыми.
String[] list() Чтение массива наименований файлов и подкаталогов.
File[] listFiles() Чтение массива файлов и подкаталогов.
boolean mkdir() Создание нового каталога.
boolean renameTo(File dest) Переименовывание файла или каталога.

В следующем примере открываем файл «d:/test/MyFile.txt» (Windows) и извлекаем его характеристики:

import java.io.File; public class FileTest < public static void main(String args[]) < File fl = new File("d:\\test\\MyFile.txt"); System.out.println ("Имя файла: " + fl .getName()); System.out.println ("Путь: " + fl.getPath()); System.out.println ("Полный путь: " + fl.getAbsolutePath()); System.out.println ("Родительский каталог: " + fl.getParent()); System.out.println (fl.exists() ? "Файл существует" : "Файл не существует"); System.out.println (fl.canWrite() ? "Свойство - можно записывать" : "Свойство - нельзя записывать"); System.out.println (fl.canRead() ? "Свойство - можно читать" : "Свойство - нельзя читать"); System.out.println ("Это директория ? " + (fl.isDirectory() ? "да": " нет")); System.out.println ("Это обычный файл ? " + (fl.isFile() ? "да" : "нет")); System.out.println ("Последняя модификация файла : " + fl. lastModified()); System.out.println ("Размер файла : " + fl.length() + " bytes"); >>

В консоли будет отпечатана следующая информация:

Имя файла: MyFile.txt Путь: d:\test\MyFile.txt Полный путь: d:\test\MyFile.txt Родительский каталог: d:\test Файл существует Свойство - можно записывать Свойство - можно читать Это директория ? нет Это обычный файл ? да Последняя модификация файла : 1441710053162 Размер файла : 12 bytes

Интерфейс FileFilter

Класс File включает метод, позволяющий прочитать список только определенных файлов.

public File[] listFiles(FileFilter filter)

В отличие от одноименного метода, но без параметра, данный метод отбирает только те файлы каталога, которые удовлетворяют определенному условию. Параметр filter предназначен для задания этого условия. При этом тип параметра FileFilter — это не класс, а интерфейс, который имеет всего один метод, возвращающий true, если файл удовлетворяет определенным условиям, и false в противном случае.

public boolean accept(File pathname)

Метод listFiles будет вызывать метод accept для каждого файла в каталоге, и те, для которых accept вернет true, будут включены в результирующий список. Остальные будут проигнорированы.

Читайте также:  Java public class inner class

Для использования FileFilter необходимо создать объект и определить в нем соответствующий метод accept.

class Filter implements FileFilter < String[] ext; Filter(String ext) < this.ext = ext.split(","); >private String getExtension(File pathname) < String filename = pathname.getPath(); int i = filename.lastIndexOf('.'); if ((i >0) && (i < filename.length()-1)) < return filename.substring(i+1).toLowerCase(); >return ""; > public boolean accept(File pathname) < if (!pathname.isFile()) return false; String extension = getExtension(pathname); for (String e : ext) < if (e.equalsIgnoreCase(extension)) return true; >return false; > >

Пример использования фильтра FileFilter

import java.io.File; import java.io.FileFilter; public class FileTest < public static void main(String args[]) < // Определение директории File dir = new File("."); // Чтение полного списка файлов каталога File[] lst1 = dir.listFiles(); // Чтение списка файлов каталога // с расширениями "png" и "jpg" File[] lst2 = dir.listFiles(new Filter("png,jpg")); System.out.println ("lst1.length = " + lst1.length + ", lst2.length = " + lst2.length); >>

Чтение содержимого файла FileInputStream

Для чтения содержимого файла можно использовать класс FileInputStream, который является наследником класса InputStream и реализует все его методы. Конструктор класса FileInputStream :

FileInputStream(String fileName) throws FileNotFoundException

Если файл не может быть открыт то генерируется исключение FileNotFoundException.

Пример считывания данных из файла и вывод содержимого в консоль:

import java.io.FileInputStream; public class FilesApp < public static void main(String[] args) < try < FileInputStream fis; fis=new FileInputStream("C:\\test_dir\\test.txt"); System.out.println("Размер файла: " + fis.available() + " байт(а)"); int i = -1; while(( i = fis.read()) != -1)< System.out.print((char)i); >fis.close(); > catch(IOException e) < System.out.println(e.getMessage()); >> >

Данные файла можно считать в массив байтов :

byte[] buffer = new byte[fis.available()]; // чтение файла в буфер fis.read (buffer, 0, fis.available()); System.out.println («Содержимое файла:»); for(int i = 0; i

Класс FileInputStream предназначен прежде всего для работы с двоичными файлами. Его можно использовать для работы с текстовыми файлами, но все же для этой задачи больше подходят другие классы.

Пример использования FileInputStream для чтения файла свойств в кодировке UTF-8:

Файл свойств «data.properties» в кодировке UTF-8:

# # Параметры сервера SMTP # company=Рога и копыта manager=Остап Бендер
import java.io.Reader; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.Properties; public class Main < public static void main(String[] args) < try < InputStream is; is = new FileInputStream("data.properties"); if (is != null) < Reader reader; reader = new InputStreamReader(is, "UTF-8"); Properties props = new Properties(); props.load(reader); System.out.println ( props.getProperty ("company") + ", " props.getProperty ("manager")); is.close(); >> catch (IOException e) < e.printStackTrace(); >> >

Запись в файл FileOutputStream

Класс FileOutputStream, является производным от класса OutputStream, поэтому наследует всю его функциональность.

Пример записи строки в файл:

import java.io.FileOutputStream; public class FilesApp < public static void main(String[] args) < String text = "Hello world!"; // строка для записи try < FileOutputStream fos; fos=new FileOutputStream("C:\\test_dir\\test.txt"); // перевод строки в байты byte[] buffer = text.getBytes(); fos.write(buffer, 0, buffer.length); >catch(IOException e) < System.out.println(e.getMessage()); >> >

Для создания объекта FileOutputStream используется конструктор, принимающий в качестве параметра путь к файлу для записи. Для записи строки ее сначала переводим в массив байт и с помощью метода write строка записывается в файл. Необязательно записывать весь массив байтов. Используя перегрузку метода write(), можно записать и одиночный байт:

fos.write(buffer[0]); // запись только первого байта

Пример перезаписи содержимого из одного файла в другой:

import java.io.FileInputStream; import java.io.FileOutputStream; public class FilesApp < public static void main(String[] args) < try < FileInputStream fis; FileOutputStream fos; fis=new FileInputStream("C:\\test_dir\\test.txt"); fos=new FileOutputStream("C:\\test_dir\\new.txt"); byte[] buffer = new byte[fis.available()]; // считываем буфер fis.read(buffer, 0, buffer.length); // записываем из буфера в файл fos.write(buffer, 0, buffer.length); fis.close(); fos.close(); >catch(IOException e) < System.out.println(e.getMessage()); >> >

Класс FileOutputStream предназначен прежде всего для записи двоичных файлов. Его можно использовать для работы с текстовыми файлами, но все же для этой задачи больше подходят другие классы.

Читайте также:  Как поднять изображение вверх html

Источник

Java: List Files in a Directory

A lot of applications handle files in some way and file manipulation is one of the core knowledges in any programming language.

In order to manipulate files, we need to know where they’re located. Having an overview of files in a directory is paramount if we want to accomplish this, especially if we can perform operations on them through iteration. There are several ways to do this in Java, which we’ll show throughout this article.

For the sake of simplicity, all examples will be written for the following file tree:

Programming |-- minimax.c |-- super_hack.py |-- TODO.txt `-- CodingMusic |-- Girl Talk - All Day.mp3 |-- Celldweller - Frozen.mp3 |-- Lim Taylor - Isn't It Wonderful.mp3 `-- Radiohead - Everything in Its Right Place.mp3 

File.list()

The simplest method to list the names of files and folders in a given directory, without traversing the sub-directories, is the helper method .list() , which returns an array of String s.

We do this by using the .list() method on a File instance:

public class Pathnames < public static void main(String[] args) < // Creates an array in which we will store the names of files and directories String[] pathnames; // Creates a new File instance by converting the given pathname string // into an abstract pathname File f = new File("D:/Programming"); // Populates the array with names of files and directories pathnames = f.list(); // For each pathname in the pathnames array for (String pathname : pathnames) < // Print the names of files and directories System.out.println(pathname); > > > 

Using a simple for-each loop, we iterate through the array and print out the String s.

CodingMusic minimax.c super_hack.py TODO.txt 

Using this approach, all of the items in the CodingMusic directory aren’t shown, and a downside to this approach is that we can’t really do anything to the files themselves. We’re just getting their names. It’s useful when we just want to take a look at the files at face-value.

FilenameFilter

Another thing we can do with the .list() method is to create a FilenameFilter to return only the files we want:

File f = new File("D:/Programming"); // This filter will only include files ending with .py FilenameFilter filter = new FilenameFilter() < @Override public boolean accept(File f, String name) < return name.endsWith(".py"); > >; // This is how to apply the filter pathnames = f.list(filter); 

Running this piece of code would yield:

File.listFiles()

Similar to the previous method, this one can be used to return the names of files and directories, but this time we get them as an array of File objects, which gives us the ability to directly manipulate them:

public class Pathnames < public static void main(String args[]) < // try-catch block to handle exceptions try < File f = new File("D:/Programming"); FilenameFilter filter = new FilenameFilter() < @Override public boolean accept(File f, String name) < // We want to find only .c files return name.endsWith(".c"); > >; // Note that this time we are using a File class as an array, // instead of String File[] files = f.listFiles(filter); // Get the names of the files by using the .getName() method for (int i = 0; i < files.length; i++) < System.out.println(files[i].getName()); >> catch (Exception e) < System.err.println(e.getMessage()); >> > 

Now, let’s traverse deeper into the file system using recursion and some more methods to use on the File object:

public class ListFilesRecursively < public void listFiles(String startDir) < File dir = new File(startDir); File[] files = dir.listFiles(); if (files != null && files.length > 0) < for (File file : files) < // Check if the file is a directory if (file.isDirectory()) < // We will not print the directory name, just use it as a new // starting point to list files from listDirectory(file.getAbsolutePath()); > else < // We can use .length() to get the file size System.out.println(file.getName() + " (size in bytes: " + file.length()+")"); > > > > public static void main(String[] args) < ListFilesRecursively test = new ListFilesRecursively(); String startDir = ("D:/Programming"); test.listFiles(startDir); > > 
Girl Talk - All Day.mp3 (size in bytes: 8017524) Celldweller - Frozen.mp3 (size in bytes: 12651325) Lim Taylor - Isn't It Wonderful.mp3 (size in bytes: 6352489) Radiohead - Everything in Its Right Place.mp3 (size in bytes: 170876098) minimax.c (size in bytes: 20662) super_hack.py (size in bytes: 114401) TODO.txt (size in bytes: 998) 

Files.walk()

In Java 8 and later we can use the java.nio.file.Files class to populate a Stream and use that to go through files and directories, and at the same time recursively walk all subdirectories.

Читайте также:  Write compiler using python

Note that in this example we will be using Lambda Expressions:

public class FilesWalk < public static void main(String[] args) < try (Stream walk = Files.walk(Paths.get("D:/Programming"))) < // We want to find only regular files List result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); > catch (IOException e) < e.printStackTrace(); >> > 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Here, we’ve populated a Stream using the .walk() method, passing a Paths argument. The Paths class consists of static methods that return a Path based on a String URI — and using a Path , we can locate the file easily.

The Path , Paths , Files , and many other classes belong to the java.nio package, which was introduced in Java 7 as a more modern way to represent files in a non-blocking way.

Then, using the Collections Framework, a list is generated.

Running this piece of code will yield:

D:\Programming\Coding Music\Radiohead - Everything in Its Right Place.mp3 D:\Programming\Coding Music\Lim Taylor - Isn't It Wonderful.mp3 D:\Programming\Coding Music\Celldweller - Frozen.mp3 D:\Programming\Coding Music\Girl Talk - All Day.mp3 D:\Programming\minimax.c D:\Programming\super_hack.py D:\Programming\TODO.txt 

Conclusion

Handling files in some way is a core task for most programming languages, and this includes the ability to list and find files in the file system. In order to manipulate files, we need to know where they’re located. Having an overview of files in a directory is paramount if we want to accomplish this, especially if we can perform operations on them through iteration.

In this article we showed a number of different ways in Java to list files on the file system, using both linear and recursive approaches.

Источник

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