Java get file info

Как получить информацию о файле в Java?

В данном примере я покажу Вам как можно получить информацию о файле в Java. Итак, код:

файл JavaFileInfo.java

import java.io.*;
import java.util.*;

/**
* Программа, которая показывает информацию о файле
*/
public class JavaFileInfo
public static void main(String[] argv) throws IOException
// проверяем на правильность вызова программы
if (argv.length == 0) System.err.println(«Используется так: » + JavaFileInfo.class.getName() + » имя_файла.txt»);
System.exit(1);
>

// проходимся по каждому переданному названию файла
for (String arg: argv) getFileStatus(arg);
>
>

public static void getFileStatus(String fileName) throws IOException
System.out.println(«—» + fileName + «—«);

// Создаем объект File для заданного имени
File file = new File(fileName);

// Проверяем файл на существование
if (!file.exists()) System.out.println(«Файл не найден\n»);
return;
>

// Выводим в консоль полное название файла
System.out.println(«Полное название » + file.getCanonicalPath());
// Выводим родительскую папку, если возможно
String fileParent = file.getParent();
if (fileParent != null) System.out.println(«Родительская папка: » + fileParent);
>

// Проверяем права доступа к файлу
if (file.canRead()) System.out.println(«Файл может быть прочитан»);
>

// Проверка на возможность записи в файл
if (file.canWrite()) System.out.println(«Данные могут быть записаны в файл»);
>

// Выводим дату изменения файла
Date date = new Date();
date.setTime(file.lastModified());
System.out.println(«Файл изменен: » + date);

// Если файл является именно файлом, а не папкой, например
if (file.isFile()) // Выводим в консоль размер файла в байтах
System.out.println(«Размер файла: » + file.length() + » байт(а).»);
> else if (file.isDirectory()) System.out.println(«Это папка»);
> else System.out.println(«Путь и не файл и не папка»);
>

System.out.println(); // добавляем перевод строки

$ java JavaFileInfo hello.pdf report.pdf

—/home/myruakov/pdfs/file.pdf—
Полное название /home/myruakov/pdfs/file.pdf
Родительская папка: /home/myruakov/pdfs
Файл может быть прочитан
Данные могут быть записаны в файл
Файл изменен: Mon Sep 08 07:24:38 MSK 2021
Размер файла: 800283 байт(а).

Читайте также:  Вывод div в php

Таким образом, мы сделаи простую программу, которая выдает нам статистическую информацию о файле или файлах.

Создано 13.01.2022 08:47:46

  • Николай
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Java — get file information

    Alicia-Lambert

    In this article, we would like to show you how to get file information in Java.

    There are several methods to get file information in Java.io.File package:

    • getName() — returns the name of the given file object,
    • getAbsolutePath() — returns the absolute pathname of the given file object,
    • canWrite() — returns a boolean value representing whether the application is allowed to write the file or not,
    • canRead() — returns a boolean value representing whether the application is allowed to read the file or not,
    • getParent() — returns a String value which is the path of the Parent of the given file object,
    • length() — returns the length of the file in bits.
    Читайте также:  Замена блока только css

    Practical example

    import java.io.File; public class Example < public static void main(String[] args) < File file = new File("C:\\projects\\dirask.txt"); if (file.exists()) < System.out.println("file name: " + file.getName()); System.out.println("absolute path: " + file.getAbsolutePath()); System.out.println("writeable: " + file.canWrite()); System.out.println("readable " + file.canRead()); System.out.println("parent path: " + file.getParent()); System.out.println("file size in bytes " + file.length()); >else < System.out.println("File doesn't exist."); >> >

    Alternative titles

    Our content is created by volunteers — like Wikipedia. If you think, the things we do are good, donate us. Thanks!

    Источник

    Java Program to Get the Basic File Attributes

    Basic File Attributes are the attributes that are associated with a file in a file system, these attributes are common to many file systems. In order to get the basic file attributes, we have to use the BasicFileAttributes interface. This interface is introduced in 2007 and is a part of the nio package.

    The basic file attributes contain some information related to files like creation time, last access time, last modified time, size of the file(in bytes), this attributes also tell us that whether the file is regular or not, whether the file is a directory, or whether the file is a symbolic link or whether the file is something is other than a regular file, directory, or symbolic link.

    Methods that are used to get the basic file attributes are:

    Return Type Method Name And Description
    FileTime creationTime() – This method is used to get the creation time of the file.
    FileTime lastAccessTime() – This method is used to get the last access time of the file
    FileTime lastModifiedTime() – This method is used to get the last modified time of the file.
    long size() – This method is used to get the size of the file.
    boolean isDirectory() – This method is used to check whether the file is a directory or not.
    boolean isSymbolicLink() – This method is used to check whether the file is a symbolic link or not.
    boolean isRegularFile() – This method is used to check whether the file is regular or not.
    boolean isOther() – This method is used to check whether the file is something other than a regular file, or directory, or symbolic link.
    Читайте также:  Student management system in php code

    Below is the Java Program to get the basic file attributes:

    Источник

    Java-Buddy

    The previous post describe how to «Get file info using java.io.File», this one have similar function using java.nio.file.Path and java.nio.file.Files.

    Please note that JavaFX FileChooser return a java.io.File object. To obtain coresponding java.nio.file.Path object, call its toPath() method.

    package javafx_niofile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaFX_NIOFile extends Application < Label label; @Override public void start(Stage primaryStage) < Button btnLoad = new Button(); btnLoad.setText("Load File"); btnLoad.setOnAction(btnLoadEventListener); label = new Label(); VBox rootBox = new VBox(); rootBox.getChildren().addAll(btnLoad, label); Scene scene = new Scene(rootBox, 400, 350); primaryStage.setTitle("java-buddy.blogspot.com"); primaryStage.setScene(scene); primaryStage.show(); >public static void main(String[] args) < launch(args); >EventHandler btnLoadEventListener = new EventHandler() < @Override public void handle(ActionEvent t) < FileChooser fileChooser = new FileChooser(); //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("ALL files (*.*)", "*.*"); fileChooser.getExtensionFilters().add(extFilter); //Show open file dialog, return a java.io.File object File file = fileChooser.showOpenDialog(null); //obtain a java.nio.file.Path object Path path = file.toPath(); String fileInfo = "Path = " + path.toString() + "\n\n"; fileInfo += "FileSystem: " + path.getFileSystem() + "\n\n"; fileInfo += "FileName = " + path.getFileName() + "\n" + "Parent = " + path.getParent() + "\n\n" + "isExecutable(): " + Files.isExecutable(path) + "\n" + "isReadable(): " + Files.isReadable(path) + "\n" + "isWritable(): " + Files.isWritable(path) + "\n"; try < fileInfo += "getLastModifiedTime(): " + Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS) + "\n" + "size(): " + Files.size(path) + "\n"; >catch (IOException ex) < Logger.getLogger(JavaFX_NIOFile.class.getName()).log(Level.SEVERE, null, ex); >label.setText(fileInfo); > >; >
    Get file info using java.nio.file.Path and java.nio.file.Files
    Get file info using java.nio.file.Path and java.nio.file.Files

    Источник

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