Java program class file

Java program class file

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

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

File(String путь_к_каталогу) File(String путь_к_каталогу, String имя_файла) File(File каталог, String имя_файла)
// создаем объект File для каталога File dir1 = new File("C://SomeDir"); // создаем объекты для файлов, которые находятся в каталоге File file1 = new File("C://SomeDir", "Hello.txt"); File file2 = new File(dir1, "Hello2.txt");

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

  • boolean createNewFile() : создает новый файл по пути, который передан в конструктор. В случае удачного создания возвращает true, иначе false
  • boolean delete() : удаляет каталог или файл по пути, который передан в конструктор. При удачном удалении возвращает true.
  • boolean exists() : проверяет, существует ли по указанному в конструкторе пути файл или каталог. И если файл или каталог существует, то возвращает true, иначе возвращает false
  • String getAbsolutePath() : возвращает абсолютный путь для пути, переданного в конструктор объекта
  • String getName() : возвращает краткое имя файла или каталога
  • String getParent() : возвращает имя родительского каталога
  • boolean isDirectory() : возвращает значение true, если по указанному пути располагается каталог
  • boolean isFile() : возвращает значение true, если по указанному пути находится файл
  • boolean isHidden() : возвращает значение true, если каталог или файл являются скрытыми
  • long length() : возвращает размер файла в байтах
  • long lastModified() : возвращает время последнего изменения файла или каталога. Значение представляет количество миллисекунд, прошедших с начала эпохи Unix
  • String[] list() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге
  • File[] listFiles() : возвращает массив файлов и подкаталогов, которые находятся в определенном каталоге
  • boolean mkdir() : создает новый каталог и при удачном создании возвращает значение true
  • boolean renameTo(File dest) : переименовывает файл или каталог

Работа с каталогами

Если объект File представляет каталог, то его метод isDirectory() возвращает true . И поэтому мы можем получить его содержимое — вложенные подкаталоги и файлы с помощью методов list() и listFiles() . Получим все подкаталоги и файлы в определенном каталоге:

import java.io.File; public class Program < public static void main(String[] args) < // определяем объект для каталога File dir = new File("C://SomeDir"); // если объект представляет каталог if(dir.isDirectory()) < // получаем все вложенные объекты в каталоге for(File item : dir.listFiles())< if(item.isDirectory())< System.out.println(item.getName() + " \t folder"); >else < System.out.println(item.getName() + "\t file"); >> > > >

Теперь выполним еще ряд операций с каталогами, как удаление, переименование и создание:

import java.io.File; public class Program < public static void main(String[] args) < // определяем объект для каталога File dir = new File("C://SomeDir//NewDir"); boolean created = dir.mkdir(); if(created) System.out.println("Folder has been created"); // переименуем каталог File newDir = new File("C://SomeDir//NewDirRenamed"); dir.renameTo(newDir); // удалим каталог boolean deleted = newDir.delete(); if(deleted) System.out.println("Folder has been deleted"); >>

Работа с файлами

Работа с файлами аналогична работе с каталога. Например, получим данные по одному из файлов и создадим еще один файл:

import java.io.File; import java.io.IOException; public class Program < public static void main(String[] args) < // определяем объект для каталога File myFile = new File("C://SomeDir//notes.txt"); System.out.println("File name: " + myFile.getName()); System.out.println("Parent folder: " + myFile.getParent()); if(myFile.exists()) System.out.println("File exists"); else System.out.println("File not found"); System.out.println("File size: " + myFile.length()); if(myFile.canRead()) System.out.println("File can be read"); else System.out.println("File can not be read"); if(myFile.canWrite()) System.out.println("File can be written"); else System.out.println("File can not be written"); // создадим новый файл File newFile = new File("C://SomeDir//MyFile"); try < boolean created = newFile.createNewFile(); if(created) System.out.println("File has been created"); >catch(IOException ex) < System.out.println(ex.getMessage()); >> >

При создании нового файла метод createNewFile() в случае неудачи выбрасывает исключение IOException , поэтому нам надо его отлавливать, например, в блоке try. catch, как делается в примере выше.

Читайте также:  Основы PHP

Источник

Java Class File

A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know that a single Java programming language source file (or we can say .java file) may contain one class or more than one class. So if a .java file has more than one class then each class will compile into a separate class files.
For Example: Save this below code as Test.java on your system.

For Compiling:

After compilation there will be 3 class files in corresponding folder named as:

A single class file structure contains attributes that describe a class file.
Representation of Class File Structure

Elements of class file are as follows:

  1. magic_number: The first 4 bytes of class file are termed as magic_number. This is a predefined value which the JVM use to identify whether the .class file is generated by valid compiler or not. The predefined value will be in hexadecimal form i.e. 0xCAFEBABE.
    Now let’s see what happen when JVM will not find valid magic number. Suppose we have a .java file named as Sample.java as follows and follow step by step process on your system.
// class Declaration class Sample < public static void main(String[] args) < System.out.println("Magic Number"); >>

Step 1: Compile using javac Sample.java
Step 2: Now open the Sample.class file. It will looks like following.

Sample.class File

Runtime Exception Due to Invalid magic number

Step 3: Now erase at least single symbol from this Sample.class file from starting of file and save it.
Step 4: Now try to run this using java Sample command and see the magic i.e. you will get run time exception (See the highlighted text in below image):

Читайте также:  Можно ли завести питона дома

Note: This can vary depending on how much you remove the .class file data.

Note: Lower version compiler generated .class file can be executed by high version JVM but higher version compiler generated .class file cannot be executed by lower version JVM. If we will try to execute we will get run time exception.

This demonstration is for Windows OS as follows:

Step 1: Open a command prompt window and try to check java compiler version and JVM version using following commands respectively (Highlighted text in image are the commands)
Output for 1.8 version will be:
Java Compiler Version
JVM Version

Step 2: Now check with another version which may be higher or lower than already installed.thisDownload link.
And install this to your PC or laptops and note the installation address.
Step 3: Open a second command prompt window and set the path of bin folder of installed jdk installed during 2nd step. And check for Java compiler version ad JVM version.
Checking Version of JDK 1.6
Step 4: Now on 1st command prompt compile the any valid .java file. For example: See above Sample.java file. Compile it as:
Compiling with Compiler Version 1.8
Step 5: Now on 2nd command prompt window try to run the above compiled code class file and see what happen. There is a run time exception which I have highlighted in below image.

Runtime Exception Due to Invalid major and minor Version of class file

Note: Internally jdk 1.5 version means 49.0 and 1.6 means 50.0 and 1.7 means 51.0 etc. class file version where the digits before the decimal point represent the major_version and digits after decimal point represents the minor_version.

  1. constant_pool_count: It represents the number of the constants present in the constant pool (When a Java file is compiled, all references to variables and methods are stored in the class’s constant pool as a symbolic reference).
  2. constant_pool[]: It represents the information about constants present in constant pool file.
  3. access_flags: It provide the information about the modifiers which are declared to the class file.
  4. this_class: It represents fully qualified name of the class file.
  5. super_class: It represents fully qualified name of the immediate super class of current class. Consider above Sample.java file. When we will compile it, then we can say this_class will be Sample class and super_class will be Object class.
  6. interface_count: It returns the number of interfaces implemented by current class file.
  7. interface[]: It returns interfaces information implemented by current class file.
  8. fields_count: It represents the number of fields (static variable) present in current class file.
  9. fields[]: It represent fields (static variable) information present in current class file.
  10. method_count: It represents number of methods present in current class file.
  11. method[]: It returns information about all methods present in current class file.
  12. attributes_count: It returns the number of attributes (instance variables) present in current class file.
  13. attributes[]: It provides information about all attributes present in current class file.
Читайте также:  Java string intern pool

Источник

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