Java学习作业(14.4.21)

前三次作业都是基础语法。真的好水啊。从这次开始记录。

1.编写Java程序,把当前目录下扩展名为txt的文件的扩展名全部更名为back。

 1 import java.io.*;
 2 import java.lang.*;
 3 
 4 
 5 public class Home { 
 6     
 7     public void reName(String path, String from, String to) { 
 8         File f = new File(path);    //声明File对象,用于导入修改路径
 9         File[] fs = f.listFiles();   //声明File对象数组,用于存储f目录下的文件
10         for (int i = 0; i < fs.length; ++i) { 
11             File f2 = fs[i];     //通过对各个文件的遍历,通过f2 取出各个文件
12             if (f2.isDirectory()) { 
13                 reName(f2.getPath(), from, to); //如果f2 是一个目录,则递归调用reName,更改子目录中的文件
14             } else { 
15                 String name = f2.getName(); 
16                 if (name.endsWith(from)) { //否则更改该文件下文件
17                     f2.renameTo(new File(f2.getParent() + "/" + name.substring(0, name.indexOf(from)) + to)); 
18                 } 
19             } 
20         }
21         
22         System.out.print("文件修改成功 
");
23         System.out.print("请到文件目录下查看修改:
");
24     }
25     
26     public static void main(String[] args) { 
27         Home rf = new Home(); 
28         rf.reName("D:\Desgard_Duan\作业\", ".txt", ".back");
29     } 
30 }  

(一开始用eclipse成功运行,但是用控制台一直报“NullPointerError”,在9行后增加了如下代码,成果解决。感谢憨大哥。)

1 if (fs == null) {
2     System.out.println("目录中无法获取文件,程序退出。");
3     System.exit(0);
4 }

2. 编写程序,用命令行参数实现比较两个文件是否长度和内容完全相同,输出比较结果(用Yes和No表示)。

 1 import java.io.*;
 2 import java.lang.*;
 3 
 4 
 5 public class Home2 { 
 6     private String file1 = null;  //用来存储对比的两个文件名
 7     private String file2 = null;
 8     
 9     public Home2(String file1, String file2) {
10         this.file1 = file1;
11         this.file2 = file2;
12     }
13     
14     private void cmpFile(String file1, String file2) {
15         try {
16             BufferedInputStream inFile1 = new BufferedInputStream(new 
17                     FileInputStream(file1));
18             BufferedInputStream inFile2 = new BufferedInputStream(new
19                     FileInputStream(file2));
20             //long startTime = System.currentTimeMillis();  //计算毫秒数
21             if(inFile1.available() == inFile2.available()) {
22                 while(inFile1.read() != -1 && inFile2.read() != -1) { //如果文件没有读取到文件结尾处
23                     if(inFile1.read() != inFile2.read()) {
24                         System.out.println("No");
25                         break;
26                     }
27                 }
28                 System.out.println("Yes");
29             } else {
30                 System.out.println("No");
31             }
32             inFile1.close();
33             inFile2.close();
34             System.exit(0);
35         } catch(IOException error) {
36             error.printStackTrace();
37         }
38     }
39     
40     private static String inputFileName() {
41         String fileName = null;
42         BufferedReader buffRead1 = new BufferedReader(new InputStreamReader(System.in)); //通过缓存方式读取文本,由Reader类扩展而来
43         try {
44             fileName = buffRead1.readLine(); 
45         } catch(IOException error) {
46             error.printStackTrace();
47         }
48         return fileName;
49     }
50     
51     public static void main(String[] args) {
52         System.out.println("please input the two files' full path and name:");
53         System.out.print("File1:");
54         String file1 = inputFileName();
55         System.out.print("File2:");
56         String file2 = inputFileName();
57         Home2 fileCompare = new Home2(file1, file2);
58         fileCompare.cmpFile(file1, file2);
59     }
60 }  

(此题没有什么难度,只要用学会文件读取,逐个字符进行检查即可。在编写包内类的时候,最好的习惯是给每个成员写入set和get方法,笔者有些偷懒。)

3.编写控制台(字符界面)应用程序,实现文件按字节异或加密。要求输入一字节密钥key和源文件名。建立加密文件,加密文件第1字节为密钥key,以后各字节为源文件各字节与密钥进行异或运算的结果编写另程序实现解密(由加密文件还原源文件)。此题鼓励同学自拟图形界面,综合运用对话框或视窗、文件对话框、多种Component、事件响应来实现加密解密功能。

import java.util.*;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class Text {
    Frame f = new Frame("文件加/解密GUI演示");
    MenuBar mb = new MenuBar();
    Menu me = new Menu("功能");
    NewPanel p = new NewPanel();
    
    Text() {
        me.add(new MenuItem("加密"));
        me.add(new MenuItem("解密"));
        me.add(new MenuItem("-"));
        me.add(new MenuItem("退出"));
        mb.add(me);
        
        f.setMenuBar(mb);
        f.add(p);
        f.setSize(new Dimension(600, 300));
        f.setLocation(400, 200);
        f.setVisible(true);
        
        me.addActionListener(p);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
    
    public static void main(String[] args) {
        new Text();
    }
    
    class NewPanel extends Panel implements ActionListener {
        Label la1 = new Label();
        Label la2 = new Label();
        Label la3 = new Label();
        Button bu1 = new Button("打开");
        Button bu2 = new Button("打开");
        Button bu3 = new Button();
        TextField tf = new TextField(4);
        Panel p1 = new Panel();
        Panel p2 = new Panel();
        Panel p3 = new Panel();
        File file1 = null, file2 = null;
        
        NewPanel() {
            p1.add(la1); p1.add(bu1);
            p2.add(la2); p2.add(bu2);
            p3.add(la3); p3.add(tf); p3.add(bu3);
            
            this.setLayout(new BorderLayout());
            this.add("North", p1); p1.setVisible(false);
            this.add("Center", p2); p2.setVisible(false);
            this.add("South", p3); p3.setVisible(false);
            
            bu1.addActionListener(this);
            bu2.addActionListener(this);
            bu3.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == bu1) {
                FileDialog fd = new FileDialog(f, "打开文件");
                fd.setVisible(true);
                if (fd.getFile() != null) {
                    file1 = new File(fd.getDirectory() + fd.getFile());
                    la1.setText("第一个文件:" + file1.getAbsolutePath());
                }
            } else if (e.getSource() == bu2) {
                FileDialog fd = new FileDialog(f, "打开文件");
                fd.setVisible(true);
                if (fd.getFile() != null) {
                    file2 = new File(fd.getDirectory() + fd.getFile());
                    la2.setText("第二个文件:" + file2.getAbsolutePath());
                }
            } else if (e.getSource() == bu3 && e.getActionCommand() == "加密") {
                try {
                    BufferedInputStream bis = new BufferedInputStream(
                            new FileInputStream(file1));
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(file2));
                    
                    // write key
                    int key = Integer.parseInt(tf.getText());
                    bos.write(key);
                    for (int _; (_ = bis.read()) >= 0; ) bos.write(_^key);
                    bis.close(); 
                    bos.close();
                    la3.setText("加密成功"); 
                    tf.setVisible(false);
                    bu3.setVisible(false);
                    p3.setVisible(true);
                } catch (IOException _) {
                }
            } else if (e.getSource() == bu3 && e.getActionCommand() == "解密") {
                try {
                    BufferedInputStream bis = new BufferedInputStream(
                            new FileInputStream(file1));
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(file2));
                    
                    int key = bis.read();
                    if (key < 0) {
                    } else {
                        for (int _; (_ = bis.read()) >= 0; ) bos.write(_^key);
                    }
                    
                    bis.close(); 
                    bos.close();
                    la3.setText("解密成功");
                    la3.setVisible(true);
                    tf.setVisible(false);
                    bu3.setVisible(false);
                    p3.setVisible(true);
                } catch (IOException _) {
                }
            } else if (e.getActionCommand() == "加密") {
                la1.setText("选择需加密文件:"); 
                p1.setVisible(true);
                la2.setText("选择加密到文件:");
                p2.setVisible(true);
                la3.setText("请输入密匙(1~255):");
                la3.setVisible(true);
                tf.setVisible(true);
                bu3.setLabel("加密");
                bu3.setVisible(true);
                p3.setVisible(true);
            } else if (e.getActionCommand() == "解密") {
                la1.setText("选择需解密文件:"); 
                p1.setVisible(true);
                la2.setText("选择解密到文件:");
                p2.setVisible(true);
                la3.setText("请输入密匙(1~255):");
                bu3.setLabel("解密");
                bu3.setVisible(true);
                la3.setVisible(false);
                tf.setVisible(false);
                p3.setVisible(true);
            } else if (e.getActionCommand() == "退出") {
                System.exit(0);
            }
            
            // 可以重排所有组件
            f.setVisible(false);
            f.setVisible(true);
        }  
    }
}

(憨大哥大代码直接抄来了。最近要准备其他事情。唉。。)

4. 输入打印行数n,打印如下字符图形到屏幕上和字符文件abc.txt中。

 1 import java.io.*;
 2 import java.lang.*;
 3 import java.util.*;
 4 
 5 
 6 public class Home4 { 
 7     public static void WriteStringToFile(String filePath, String text) {  
 8         try {  
 9             File file = new File(filePath);  
10             PrintStream ps = new PrintStream(new FileOutputStream(file));  
11             ps.println(text);
12         } catch (FileNotFoundException error) {  
13             error.printStackTrace();  
14         }  
15     } 
16     public static void main(String[] args) {
17         Scanner in = new Scanner(System.in);
18         int n = in.nextInt();
19         String text = "";
20         int num = 1;
21         for(int i = 1; i <= n; i++) {
22             for(int j = 0; j < n - i; j++) {
23                 System.out.print("	");
24                 text += "	";
25             }
26             for(int j = 1; j <= i; j++) {
27                 System.out.print(num + "	");
28                 text += String.valueOf(num);
29                 text += "	";
30                 num += 2;
31             }
32             System.out.println();
33             text += "
";
34         }
35         WriteStringToFile("abc.txt", text);
36         
37     }
38     
39 }  

(最简单的一道作业题目,不多说。)

5. 已知学生类含有实例属性(姓名、学号、成绩),实例方法(构造方法、getter方法)。建立字符文件a.txt,第一行为一个整数(表示学生人数),第二行开始,每行提供一个学生所需的实例属性值。编写程序1,从a.txt输入学生人数和学生信息,建立学生数组。将所有学生数组各元素写入二进制文件a.dat(a.dat的开头4字节为表示学生数的整数)。编写程序2,从a.dat读出学生数据输出为字符文件b.txt(输入出格式同a.txt)。编写程序3读入a.dat数据,用随机文件方式删除成绩<60分的学生记录并存回a.dat。(程序2用于检查程序1和程序2的结果是否正确)。

 

import java.io.*;
import java.util.*;
import java.text.*;

public class Text {
    public static void main(String[] args) throws Exception {
        fun_1();
    //fun_2();
    //fun_3();
    }
    
    public static void fun_1() throws IOException {
        Scanner cin = new Scanner(new File("a.txt"));
        int N = cin.nextInt();
        Student[] stu = new Student[N];
        for (int i = 0; i < N; ++i) {
            stu[i] = new Student(cin.next(), cin.next(), cin.nextFloat());
        }
        
        ObjectOutputStream oos = new ObjectOutputStream(
                new BufferedOutputStream(
                new FileOutputStream("a.dat")));
        
        oos.write(Chg.toByte(N));
        for (Student _ : stu) {
            oos.writeObject(_);
        }
        
        cin.close();
        oos.close();
    }
    
    public static void fun_2() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(
                new BufferedInputStream(
                new FileInputStream("a.dat")));
        byte[] b = new byte[4];
        ois.read(b);
        int N = Chg.toInt(b);
        
        PrintWriter pw = new PrintWriter(
                new BufferedOutputStream(
                new FileOutputStream("b.txt")));
        
        pw.printf("%d
", N);
        for (int i = 0; i < N; ++i) {
            Student stu = (Student)ois.readObject();
            DecimalFormat fmt= new DecimalFormat("###.##");
            pw.println(stu.getName() + " " + stu.getNumber() + " " + fmt.format(stu.getScore()));
        }
        ois.close();
        pw.close();
    }
    
    
    public static void fun_3() throws Exception {
        // 重写a.dat
        Scanner cin = new Scanner(new File("a.txt"));
        // RandAccessFile只有"rw"和"r",没有"w"
        RandomAccessFile oos = new RandomAccessFile("a.dat", "rw");
        
        int N = cin.nextInt();
        oos.writeInt(N);
        for (int i = 0; i < N; ++i) {
            String name = cin.next();
            String number = cin.next();
            float score = cin.nextFloat();
            
            oos.writeUTF(name);
            oos.writeUTF(number);
            oos.writeFloat(score);
        }
        
        cin.close();
        oos.close();
        
        //开始删除
        RandomAccessFile raf = new RandomAccessFile("a.dat", "rw");
        N = raf.readInt();
        int M = 0;
        
        for (int i = 0; i < N; ++i) {
            String name = raf.readUTF();
            String number = raf.readUTF();
            float score = raf.readFloat();
            
            if (score < 60) continue;
            ++M;
        }
        
        long r = 0, w = 0;
        raf.seek(0); 
        raf.readInt(); 
        r = raf.getFilePointer();
        raf.seek(0);
        raf.writeInt(M);
        w = raf.getFilePointer();
        
        for (int i = 0; i < N; ++i) {
            raf.seek(r);
            String name = raf.readUTF();
            String number = raf.readUTF();
            float score = raf.readFloat();
            r = raf.getFilePointer();
            
            if (score < 60) continue;
            raf.seek(w);
            raf.writeUTF(name);
            raf.writeUTF(number);
            raf.writeFloat(score);
            w = raf.getFilePointer();
        }
        raf.setLength(w);
        raf.close();
        
        //转换到"b.txt"
        RandomAccessFile ois = new RandomAccessFile("a.dat", "r");
        PrintWriter pw = new PrintWriter(
                new BufferedOutputStream(
                new FileOutputStream("b.txt")));
        
        N = ois.readInt();
        pw.printf("%d
", N);
        for (int i = 0; i < N; ++i) {
            String name = ois.readUTF();
            String number = ois.readUTF();
            Float score = ois.readFloat();
            
            DecimalFormat fmt= new DecimalFormat("###.##");
            pw.println(name + " " + number + " " + fmt.format(score));
        }
        ois.close();
        pw.close();
    }
}

class Student implements Serializable {
    private String name;
    private String number;
    private float score;
    
    Student() {
    }
    Student(String _name, String _number, float _score) {
        name = _name;
        number = _number;
        score = _score;
    }
    public String getName() {
        return name;
    }
    public String getNumber() {
        return number;
    }
    public float getScore() {
        return score;
    }
    public void setName(String _name) {
        name = _name;
    }
    public void setNumber(String _number) {
        number = _number;
    }
    public void setScore(float _score) {
        score = _score;
    }
}

class Chg {
    public static byte[] toByte(int x) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; ++i) {
            b[i] = (byte)(x&0xff);
            x >>= 8;
        }
        return b;
    }
    
    public static int toInt(byte[] b) {
        int x = 0;
        for (int i = 0; i <b.length; ++i)
            x |= (b[i]&0xff)<<(i*8);
        return x;
    }
}

收获:通过独立完成java课堂题目,了解了java的基本文件的方法,熟悉了处理文件十分基础的API。希望自身不断提高,争取熟练掌握文件控制。

  Desgard_Duan 写于2014.4.27    

 

原文地址:https://www.cnblogs.com/Destiny-Gem/p/3695249.html