JavaRush /Java Blog /Random-TW /第 31 級。有關該級別主題的面試問題的答案
DefNeo
等級 36

第 31 級。有關該級別主題的面試問題的答案

在 Random-TW 群組發布
第 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