JavaRush /Java 博客 /Random-ZH /第 31 级。有关该级别主题的面试问题的答案
DefNeo
第 36 级

第 31 级。有关该级别主题的面试问题的答案

已在 Random-ZH 群组中发布
第 31 级。有关第 1 级主题的面试问题的答案
  1. 一个对象可以File对应一个还不存在的文件吗?

    是的,如果您将目录值传递给构造函数。

    String dirPath = "/";
    File f = new File(dirPath);
    File[] files = f.listFiles();

    例如,这样做是为了获取文件数组。

    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);
    
        }
    }

    输出:

    真假

    File继承自object. 答:是的!我正在等待您的评论。

  2. 如何将对象转换File为类型Path

    方法toPath();

    toPath(); //Returns a java.nio.file.Path object constructed from the this abstract path.
  3. 为什么需要 Files 类?

    我们以类为基础File,添加了一些新的东西,重命名了方法,最后也将其一分为二。所以现在有两个新类 -PathFiles

    Path- 事实上,这是该类的一个新类似物File,并且Files- 这是一个实用程序类(与Arrays&类类比Collections),该类的所有静态方法都已转移给它File。从OOP.M的角度来看这是“更正确”

    一些来自文档:

    public final class Files
    extends Object

    此类仅由对文件、目录或其他类型的文件进行操作的静态方法组成。
    在大多数情况下,此处定义的方法将委托给关联的文件系统提供者来执行文件操作。

  4. 您知道哪些归档课程?

    关于这个主题的一篇好文章及其摘录:Archiving in Java

    Java 规范中有两个包用于处理档案 -java.util.zip分别java.util.jar用于 zip 和 jar 档案。jar 和 zip 格式之间的区别仅在于 zip 存档的扩展名。除了构造函数和类方法的实现之外,包与包java.util.jar类似。下面仅讨论包。要将所有示例转换为使用 zip 存档,只需将代码中各处的 Jar 替换为 Zip 即可。java.util.zipvoidputNextEntry(ZipEntry e)JarOutputStreamjava.util.jar

  5. 如何将目录添加到存档中?

    就我自己而言,我将这个问题理解为向已完成的存档添加一个空目录。我没有找到任何有效的例子。这是代码:(它清楚地表明您可以将任何文件放入存档中,但是目录为空...我不知道如何回答,我没有在StackOverFlow上发帖,这样的问题肯定会否决)如果有人有任何建议,请写下来。

    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();
            }
        }
    }

    问题是关于最后一个 testDir,JVM 不会将其放入生成的存档中,而所有其他 txt 文件都运行良好。

    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();
        }
    }

    代码来自这里

  6. 为什么需要它们Properties

    Properties是一个属性文件。其结构:键-值。为了处理此类文件,Java 有一个类Properties,它继承自HashTable<Object, Object>

    有一篇关于操作它的文章 - Java Properties file Examples

  7. 数据以什么形式存储在文件中.properties

    关键是意义。

  8. Properties从文件加载对象后是否可以更改对象中的数据?

    如果它是从 继承的HashMap,那么您可以,只有这样您才需要取消写入对此文件的更改。有一个方法可以做到这一点setProperty

    这是代码:

    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();
                    }
                }
            }
        }
    
    }

    Вывод:

    ddfdfdfdfdf

  9. Зачем нужен класс 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.

    Класс для чтения символов файлов. Конструкторы этого класса предполагают, что codeировка символов дефолтная и дефолтный размер буфера являются подходящими. Whatбы задать эти значения самостоятельно, следует построить InputStreamReader над FileInputStream. FileReader предназначен для считывания потоков символов.

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

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