JavaRush /Java Blog /Random EN /Level 31. Answers to interview questions on the level top...
DefNeo
Level 36

Level 31. Answers to interview questions on the level topic

Published in the Random EN group
Level 31. Answers to interview questions on the topic of level - 1
  1. Can an object Filecorrespond 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 false

    Fileinherits from object. Answer: yes! I'm waiting for your 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?

    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 - Pathand Files.

    Path- this is, in fact, a new analogue of the class File, and Files- this is a utility class (by analogy with the Arrays& classes Collections), all the static methods of the class have been transferred to it File. This is “more correct” from the point of view of OOP.M

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

  4. 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.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 constructors and a voidputNextEntry(ZipEntry e)class method JarOutputStream. Only the package will be discussed below java.util.jar. To convert all examples to use a zip archive, just 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 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

  6. Why are they needed Properties?

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

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

  7. In what form is the data stored in the file .properties?

    The key is the meaning.

  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 unwrite the changes to this file. There is a method for this setProperty.

    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

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

  10. 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) специально ориентированы для работы с текстом и строками.

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