-
Can an object
File
correspond to a file that doesn't exist yet?Yes, if you pass the directory value to the constructor.
String dirPath = "/"; File f = new File(dirPath); File[] files = f.listFiles();
This is done, for example, in order to obtain an array of files.
public class MyClass { public static void main(String[] args) { boolean isObject = false; File file = new File("/"); if (file instanceof Object){ isObject = true; } boolean isFile = file.isFile(); // Tests whether the file denoted by this abstract pathname is a normal file. Это из documentации System.out.println(isObject + " "+ isFile); } }
Output:
true falseFile
inherits fromobject
. Answer: yes! I'm waiting for your comments. -
How to convert an object
File
to typePath
?Method
toPath();
toPath(); //Returns a java.nio.file.Path object constructed from the this abstract path.
-
Why is the Files class needed?
We took the class as a basis
File
, added a little something new to it, renamed the methods, and at the end also divided it into two. So now there are two new classes -Path
andFiles
.Path
- this is, in fact, a new analogue of the classFile
, andFiles
- this is a utility class (by analogy with theArrays
& classesCollections
), all the static methods of the class have been transferred to itFile
. This is “more correct” from the point of view of OOP.MSome from the documents:
public final class Files
extends Object
This class consists exclusively of static methods that operate on files, directories, or other types of files.
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations. -
What archiving classes do you know?
A good article on this topic and an excerpt from it: Archiving in Java
There are two packages in the Java specification for working with archives -
java.util.zip
andjava.util.jar
respectively for zip and jar archives. The difference between jar and zip formats is only in the extension of the zip archive. A packagejava.util.jar
is similar to a packagejava.util.zip
, except for the implementation of constructors and avoidputNextEntry(ZipEntry e)
class methodJarOutputStream
. Only the package will be discussed belowjava.util.jar
. To convert all examples to use a zip archive, just replace Jar with Zip everywhere in the code. -
How to add a directory to an archive?
For myself, I understood this question as adding an empty directory to a finished archive. I didn't find any working examples. Here is the code: (It clearly shows that you can put any file in the archive, but with an empty directory... I don’t know how to answer, I didn’t post on StackOverFlow, such a question will definitely be downvoted) If anyone has any suggestions, write.
public class Main { public static void main(String[] args) { String[] myFiles = {"D:\\forJava\\MyArtifactName\\packForTest\\res2.txt", "D:\\forJava\\MyArtifactName\\packForTest\\res.txt", "D:\\forJava\\MyArtifactName\\packForTest\\res4.txt", "D:\\forJava\\MyArtifactName\\packForTest\\testDir\\" }; String zipFile = "D:\\forJava\\MyArtifactName\\packForTest\\res.zip"; ZipUtility zipUtil = new ZipUtility(); try { zipUtil.zip(myFiles, zipFile); } catch (Exception ex) { // some errors occurred ex.printStackTrace(); } } }
The question is about the last testDir, the JVM does not put it in the resulting archive, with all the other txt files it works out fine.
ZipUtility.java
:import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtility { private static final int BUFFER_SIZE = 4096; public void zip(List<File> listFiles, String destZipFile) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); for (File file : listFiles) { if (file.isDirectory()) { zipDirectory(file, file.getName(), zos); } else { zipFile(file, zos); } } zos.flush(); zos.close(); } public void zip(String[] files, String destZipFile) throws IOException { List<File> listFiles = new ArrayList<File>(); for (int i = 0; i < files.length; i++) { listFiles.add(new File(files[i])); } zip(listFiles, destZipFile); } private void zipDirectory(File folder, String parentFolder, ZipOutputStream zos) throws IOException { for (File file : folder.listFiles()) { if (file.isDirectory()) { zipDirectory(file, parentFolder + "/" + file.getName(), zos); continue; } zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); bytesRead += read; } zos.closeEntry(); } } private void zipFile(File file, ZipOutputStream zos) throws IOException { zos.putNextEntry(new ZipEntry(file.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); bytesRead += read; } zos.closeEntry(); } }
Code from here
-
Why are they needed
Properties
?Properties
is a properties file. Its structure: key – value. To work with such files, Java has a classProperties
, it is inherited fromHashTable<Object, Object>
There is an article about manipulating it - Java Properties file examples
-
In what form is the data stored in the file
.properties
?The key is the meaning.
-
Is it possible to change the data in an object
Properties
after loading it from a file?If it is inherited from
HashMap
, then you can, only then you will need to unwrite the changes to this file. There is a method for thissetProperty
.Here's the code:
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Created by Роман on 12.09.2016. */ public class LoadAndSetProperties { public static void main(String[] args) { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream("D:\\forJava\\MyArtifactName\\packForTest\\config.properties"); // load a properties file prop.load(input); // get the property value and print it out prop.setProperty("database", "ddfdfdfdfdf"); System.out.print(prop.getProperty("database")); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Output:
ddfdfdfdfdf -
Why do we need a class
FileReader
?Java Docs:
public class FileReader
extends InputStreamReader
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters.
Class for reading file symbols. The constructors of this class assume that the default character encoding and default buffer size are appropriate. To set these values yourself, you should build
InputStreamReader
overFileInputStream
.FileReader
designed to read character streams. -
Why do we need a class
FileWriter
?public class FileWriter
extends OutputStreamWriter
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open. FileWriter is meant for writing streams of characters.
Класс для записи символов файлов. Конструкторы этого класса предполагают, что codeировка символов дефолтная и дефолтный размер буфера являются приемлемым. Whatбы задать эти значения самостоятельно, следует построить
OutputStreamWriter
надFileOutputStream
. Является ли файл доступен для записи, зависит от используемой платформы. Некоторые платформы разрешают держать файл для записи только однимFileWriter
(or другого an object записи file), в одно время.FileWriter
предназначен для записи потоков символов. Для написания потоков необработанных byteов, используйтеFileOutputStream
.Эти классы (
FileReader
иFileWriter
) специально ориентированы для работы с текстом и строками.
DefNeo
Level 36
GO TO FULL VERSION