-
Can an object
File
correspond to a file that doesn't exist yet?Yes, if you pass a directory value to the constructor.
String dirPath = "/"; File f = new File(dirPath); File[] files = f.listFiles();
This is done, for example, in order to get 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
inherited fromobject
. Answer: yes! Waiting for 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?
They took the class as a basis
File
, added a little something new to it, renamed the methods, and in the end they 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 (similar to classesArrays
&Collections
), all the static methods of the class were moved into itFile
. So "correct" from the point of view of OOP.MA few from the docs:
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 classes for archiving do you know?
A good article on the subject and an excerpt from it: Archiving in Java
To work with archives in the Java specification, there are two packages -
java.util.zip
and,java.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 the constructors and thevoidputNextEntry(ZipEntry e)
class methodJarOutputStream
. Only the package will be considered belowjava.util.jar
. To convert all examples to use a zip archive, it is enough to 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 the 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, they’ll definitely downvote for such a question) If anyone has suggestions, then 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, it’s just that the JVM doesn’t put it in the resulting archive, with all the other txt files it’s normal.
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 needed
Properties
?Properties
is a properties file. Its structure: key - value. To work with such files in Java there is a classProperties
, it is inherited fromHashTable<Object, Object>
There is an article about manipulating it - Java Properties file examples
-
How is the data stored in the file
.properties
?The key is the value.
-
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 unsubscribe changes to this file. There is a method for thissetProperty
.Here is 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 is a class needed
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 characters. 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
over theFileInputStream
.FileReader
designed to read streams of characters. -
Why is a class needed
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.
Class for writing file symbols. The constructors of this class assume that the default character encoding and default buffer size are acceptable. To set these values yourself, you should build
OutputStreamWriter
over theFileOutputStream
. Whether a file is writable depends on the platform being used. Some platforms allow you to keep a file writable by only oneFileWriter
(or other file writable object) at a time.FileWriter
designed to record streams of characters. To write streams of raw bytes, useFileOutputStream
.These classes (
FileReader
andFileWriter
) are specifically designed to work with text and strings.
DefNeo
Level 36
GO TO FULL VERSION