栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

笔记 第1章 流与文件(6) 文件随机位置读取与Zip文件读取

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

笔记 第1章 流与文件(6) 文件随机位置读取与Zip文件读取

随机访问文件

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(){
 
            @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 names) {
                for(String name:names){
                    fileCombo.addItem(name);
                }
            }
        }.execute();
    }
 
    public void loadZipFile(final String name){
        fileCombo.setEnabled(false);
        fileText.setText("");
        new SwingWorker(){
 
            @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》查找相关笔记

评论点赞收藏✨关注,是送给作者最好的礼物,愿我们共同学习,一起进步

如果对作者发布的内容感兴趣,可点击下方关注公众号 钰娘娘知识汇总 查看更多作者文章哦!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/892024.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号