DefNeo
Level 36

Level 31

Published in the Random EN group
Level 31
  1. Can an object Filecorrespond 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 false

    Fileinherited from object. Answer: yes! Waiting for comments.

  2. How to convert an object Fileto type Path?

    MethodtoPath();

    toPath(); //Returns a java.nio.file.Path object constructed from the this abstract path.
  3. 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 - Pathand Files.

    Path- this is, in fact, a new analogue of the class File, and Files- this is a utility class (similar to classes Arrays& Collections), all the static methods of the class were moved into it File. So "correct" from the point of view of OOP.M

    A 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.

  4. 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.zipand, java.util.jarrespectively, for zip and jar archives. The difference between jar and zip formats is only in the extension of the zip archive. A package java.util.jaris similar to a package java.util.zip, except for the implementation of the constructors and the voidputNextEntry(ZipEntry e)class method JarOutputStream. Only the package will be considered below java.util.jar. To convert all examples to use a zip archive, it is enough to replace Jar with Zip everywhere in the code.

  5. 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

  6. Why are needed Properties?

    Propertiesis a properties file. Its structure: key - value. To work with such files in Java there is a class Properties, it is inherited fromHashTable<Object, Object>

    There is an article about manipulating it - Java Properties file examples

  7. How is the data stored in the file .properties?

    The key is the value.

  8. Is it possible to change the data in an object Propertiesafter 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 this setProperty.

    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

  9. 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 InputStreamReaderover the FileInputStream. FileReaderdesigned to read streams of characters.

  10. 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 OutputStreamWriterover the FileOutputStream. Whether a file is writable depends on the platform being used. Some platforms allow you to keep a file writable by only one FileWriter(or other file writable object) at a time. FileWriterdesigned to record streams of characters. To write streams of raw bytes, use FileOutputStream.

    These classes ( FileReaderand FileWriter) are specifically designed to work with text and strings.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION