當前位置:網站首頁>筆記 第1章 流與文件(6) 文件隨機比特置讀取與Zip文件讀取

筆記 第1章 流與文件(6) 文件隨機比特置讀取與Zip文件讀取

2022-05-14 19:42:19鈺娘娘

隨機訪問文件

RandomAccessFile: 可在文件任何比特置讀寫文件,通過設置讀寫參數"rw",判斷可進行的操作。

作者提供的示例(close關閉部分有修改):

RandomFileTest.java

🧡🤎🧡🤎🧡🤎

import java.io.*;
 
public class RandomFileTest {
    public static void main(String[] args) {
        Employee[] staff = new Employee[3];
 
        staff[0] = new Employee("Carl Cracker", 75000,1987, 12, 15);
        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
 
        DataOutputStream out = null;
        RandomAccessFile in = null;
        try{
            out = new DataOutputStream(new FileOutputStream("employee.dat"));
            for(Employee e:staff)
                e.writeData(out);
 
            in = new RandomAccessFile("employee.dat", "r");
 
            int n = (int)(in.length()/Employee.RECORD_SIZE);
            Employee[] newStaff = new Employee[n];
 
            for(int i = n-1; i >= 0; i--){
                newStaff[i] = new Employee();
                in.seek(i*Employee.RECORD_SIZE);
                newStaff[i].readData(in);
            }
 
            for(Employee e:newStaff)
                System.out.println(e);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            close(out);
            close(in);
        }
    }
     
    private static void close(Closeable c){
        if(c == null) return;
        try {
            c.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

🧡🤎🧡🤎🧡🤎

Employee.java

 

🧡🤎🧡🤎🧡🤎

import java.io.*;
 
public class RandomFileTest {
    public static void main(String[] args) {
        Employee[] staff = new Employee[3];
 
        staff[0] = new Employee("Carl Cracker", 75000,1987, 12, 15);
        staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
        staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
 
        DataOutputStream out = null;
        RandomAccessFile in = null;
        try{
            out = new DataOutputStream(new FileOutputStream("employee.dat"));
            for(Employee e:staff)
                e.writeData(out);
 
            in = new RandomAccessFile("employee.dat", "r");
 
            int n = (int)(in.length()/Employee.RECORD_SIZE);
            Employee[] newStaff = new Employee[n];
 
            for(int i = n-1; i >= 0; i--){
                newStaff[i] = new Employee();
                in.seek(i*Employee.RECORD_SIZE);
                newStaff[i].readData(in);
            }
 
            for(Employee e:newStaff)
                System.out.println(e);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            close(out);
            close(in);
        }
    }
     
    private static void close(Closeable c){
        if(c == null) return;
        try {
            c.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

🧡🤎🧡🤎🧡🤎

運行結果:

*🦽🦼*

*🦽🦼*

 1.4 ZIP文檔

ZipInputStream/ZipOutputStream 可以處理 Zip 文檔的壓縮

特別注意對於單條信息的關閉方法:zin.closeEntry()

🧡🤎🧡🤎🧡🤎

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
public class ZipTest {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                ZipTestFrame frame = new ZipTestFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}
 
class ZipTestFrame extends JFrame {
    private int WIDTH = 400;
    private int HEIGHT = 300;
    private JComboBox fileCombo;
    private JTextArea fileText;
    private String zipname;
 
    public ZipTestFrame(){
        setTitle("ZipTest");
        setSize(WIDTH,HEIGHT);
 
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
 
        JMenuItem  openItem = new JMenuItem("Open");
        menu.add(openItem);
        openItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setCurrentDirectory(new File("."));
                int r = chooser.showOpenDialog(ZipTestFrame.this);
                if(r == JFileChooser.APPROVE_OPTION){
                    zipname = chooser.getSelectedFile().getPath();
                    fileCombo.removeAllItems();
                    scanZipFile();
                }
            }
        });
 
        JMenuItem exitItem = new JMenuItem("Exit");
        menu.add(exitItem);
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
 
        menuBar.add(menu);
        setJMenuBar(menuBar);
 
        fileText = new JTextArea();
        fileCombo = new JComboBox();
        fileCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loadZipFile((String)fileCombo.getSelectedItem());
            }
        });
        add(fileCombo,BorderLayout.SOUTH);
        add(new JScrollPane(fileText),BorderLayout.CENTER);
    }
 
    public void scanZipFile(){
        new SwingWorker<Void, String>(){
 
            @Override
            protected Void doInBackground() throws Exception {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
                ZipEntry entry;
                while((entry = zin.getNextEntry())!=null){
 
                    publish(entry.getName());
                    zin.closeEntry();
                }
                zin.close();
                return null;
            }
 
            @Override
            protected void process(List<String> names) {
                for(String name:names){
                    fileCombo.addItem(name);
                }
            }
        }.execute();
    }
 
    public void loadZipFile(final String name){
        fileCombo.setEnabled(false);
        fileText.setText("");
        new SwingWorker<Void,Void>(){
 
            @Override
            protected Void doInBackground() throws Exception {
                try{
                    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
                    ZipEntry entry;
                    while((entry = zin.getNextEntry())!=null){
                        if(entry.getName().equals(name)){
                            Scanner in = new Scanner(zin);
                            while(in.hasNextLine()){
                                fileText.append(in.nextLine());
                                fileText.append("\n");
                            }
                        }
                        zin.closeEntry();
                    }
                }catch (IOException e){
                    e.printStackTrace();
                }
                return null;
            }
 
            @Override
            protected void done() {
                fileCombo.setEnabled(true);
            }
        }.execute();
    }
}

🧡🤎🧡🤎🧡🤎

運行結果:

讀取zip文件內部的文件(一層)

通過下拉框可選擇文件名,上方顯示文件內容

*🦽🦼*

實際結構:

*🦽🦼*

注意,因為新建文件夾不是文件,所以讀不出來可考慮使用遞歸結構繼續讀取子文件

相關內容:選擇 《Java核心技術 卷1》查找相關筆記

評論點贊收藏關注,是送給作者最好的禮物,願我們共同學習,一起進步

如果對作者發布的內容感興趣,可點擊下方關注公眾號 鈺娘娘知識匯總 查看更多作者文章哦!

版權聲明
本文為[鈺娘娘]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/134/202205141804256830.html

隨機推薦