Java学习作业(14.4.21)

时间:2023-03-09 18:05:53
Java学习作业(14.4.21)

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

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

 import java.io.*;
import java.lang.*; public class Home { public void reName(String path, String from, String to) {
File f = new File(path);   //声明File对象,用于导入修改路径
File[] fs = f.listFiles();   //声明File对象数组,用于存储f目录下的文件
for (int i = 0; i < fs.length; ++i) {
File f2 = fs[i];     //通过对各个文件的遍历,通过f2 取出各个文件
if (f2.isDirectory()) {
reName(f2.getPath(), from, to); //如果f2 是一个目录,则递归调用reName,更改子目录中的文件
} else {
String name = f2.getName();
if (name.endsWith(from)) { //否则更改该文件下文件
f2.renameTo(new File(f2.getParent() + "/" + name.substring(0, name.indexOf(from)) + to));
}
}
} System.out.print("文件修改成功 \n");
System.out.print("请到文件目录下查看修改:\n");
} public static void main(String[] args) {
Home rf = new Home();
rf.reName("D:\\Desgard_Duan\\作业\\", ".txt", ".back");
}
}

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

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

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

 import java.io.*;
import java.lang.*; public class Home2 {
private String file1 = null; //用来存储对比的两个文件名
private String file2 = null; public Home2(String file1, String file2) {
this.file1 = file1;
this.file2 = file2;
} private void cmpFile(String file1, String file2) {
try {
BufferedInputStream inFile1 = new BufferedInputStream(new
FileInputStream(file1));
BufferedInputStream inFile2 = new BufferedInputStream(new
FileInputStream(file2));
//long startTime = System.currentTimeMillis(); //计算毫秒数
if(inFile1.available() == inFile2.available()) {
while(inFile1.read() != -1 && inFile2.read() != -1) { //如果文件没有读取到文件结尾处
if(inFile1.read() != inFile2.read()) {
System.out.println("No");
break;
}
}
System.out.println("Yes");
} else {
System.out.println("No");
}
inFile1.close();
inFile2.close();
System.exit(0);
} catch(IOException error) {
error.printStackTrace();
}
} private static String inputFileName() {
String fileName = null;
BufferedReader buffRead1 = new BufferedReader(new InputStreamReader(System.in)); //通过缓存方式读取文本,由Reader类扩展而来
try {
fileName = buffRead1.readLine();
} catch(IOException error) {
error.printStackTrace();
}
return fileName;
} public static void main(String[] args) {
System.out.println("please input the two files' full path and name:");
System.out.print("File1:");
String file1 = inputFileName();
System.out.print("File2:");
String file2 = inputFileName();
Home2 fileCompare = new Home2(file1, file2);
fileCompare.cmpFile(file1, file2);
}
}

(此题没有什么难度,只要用学会文件读取,逐个字符进行检查即可。在编写包内类的时候,最好的习惯是给每个成员写入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中。

Java学习作业(14.4.21)

 import java.io.*;
import java.lang.*;
import java.util.*; public class Home4 {
public static void WriteStringToFile(String filePath, String text) {
try {
File file = new File(filePath);
PrintStream ps = new PrintStream(new FileOutputStream(file));
ps.println(text);
} catch (FileNotFoundException error) {
error.printStackTrace();
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String text = "";
int num = 1;
for(int i = 1; i <= n; i++) {
for(int j = 0; j < n - i; j++) {
System.out.print("\t");
text += "\t";
}
for(int j = 1; j <= i; j++) {
System.out.print(num + "\t");
text += String.valueOf(num);
text += "\t";
num += 2;
}
System.out.println();
text += "\r\n";
}
WriteStringToFile("abc.txt", text); } }

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

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\r\n", 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\r\n", 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