JavaRush /จาวาบล็อก /Random-TH /ระดับ 31 คำตอบสำหรับคำถามสัมภาษณ์ในหัวข้อระดับ
DefNeo
ระดับ

ระดับ 31 คำตอบสำหรับคำถามสัมภาษณ์ในหัวข้อระดับ

เผยแพร่ในกลุ่ม
ระดับ 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เพิ่มสิ่งใหม่เล็กน้อย เปลี่ยนชื่อวิธีการ และในตอนท้ายก็แบ่งออกเป็นสองส่วน ตอนนี้มีสองคลาสใหม่ - PathและFiles.

    Path- อันที่จริงนี่คืออะนาล็อกใหม่ของคลาสFileและFiles- นี่คือคลาสยูทิลิตี้ (โดยการเปรียบเทียบกับ คลาส Arrays& Collections) วิธีการคงที่ทั้งหมดของคลาสได้ถูกถ่ายโอนไปยังมันFileแล้ว นี่คือ "ถูกต้องมากขึ้น" จากมุมมองของ OOP.M

    บางส่วนจากเอกสาร:

    public final class Files
    extends Object

    คลาสนี้ประกอบด้วยเฉพาะวิธีการคงที่ที่ทำงานบนไฟล์ ไดเร็กทอรี หรือไฟล์ประเภทอื่นๆ
    ในกรณีส่วนใหญ่ วิธีการที่กำหนดไว้ที่นี่จะมอบหมายให้กับผู้ให้บริการระบบไฟล์ที่เกี่ยวข้องเพื่อดำเนินการกับไฟล์

  4. คุณรู้จักคลาสการเก็บถาวรอะไรบ้าง

    บทความที่ดีในหัวข้อนี้และข้อความที่ตัดตอนมาจากหัวข้อนี้: การเก็บถาวรใน Java

    มีแพ็คเกจสองแพ็คเกจในข้อกำหนด Java สำหรับการทำงานกับไฟล์เก็บถาวร - java.util.zipและjava.util.jarตามลำดับสำหรับไฟล์เก็บถาวร zip และ jar ความแตกต่างระหว่างรูปแบบ jar และ zip อยู่ที่ส่วนขยายของไฟล์ zip เท่านั้น แพคเกจjava.util.jarจะคล้ายกับแพคเกจjava.util.zipยกเว้นการดำเนินการของตัวสร้างและวิธีvoidputNextEntry(ZipEntry e)การเรียน JarOutputStreamเฉพาะแพ็คเกจเท่านั้นที่จะกล่าวถึงด้านjava.util.jarล่าง หากต้องการแปลงตัวอย่างทั้งหมดเพื่อใช้ไฟล์ zip เพียงแทนที่ Jar ด้วย Zip ทุกที่ในโค้ด

  5. จะเพิ่มไดเร็กทอรีลงในไฟล์เก็บถาวรได้อย่างไร?

    สำหรับตัวฉันเอง ฉันเข้าใจคำถามนี้ว่าเป็นการเพิ่มไดเร็กทอรีว่างลงในไฟล์เก็บถาวรที่เสร็จแล้ว ฉันไม่พบตัวอย่างการทำงานใด ๆ นี่คือโค้ด: (แสดงให้เห็นชัดเจนว่าคุณสามารถใส่ไฟล์ใดๆ ลงในไฟล์เก็บถาวรได้ แต่มีไดเร็กทอรีว่าง... ฉันไม่รู้วิธีตอบ ฉันไม่ได้โพสต์บน StackOverFlow คำถามดังกล่าวจะเป็นอย่างแน่นอน downvoted) หากใครมีข้อเสนอแนะใด ๆ เขียน

    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

  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