1.编写程序,实现读取文件时出现一个表示读取进度的进度条。可使用javax.swing包提供的输入流类ProgressMonitorInputStream。
import java.io.*;
import javax.swing.*;
public class Student {
public static void main(String[] temp) {
byte b[] = new byte[2];
try{
FileInputStream fis = new FileInputStream("word.txt");
ProgressMonitorInputStream in =
new ProgressMonitorInputStream(null,"读取文件",fis);
while(in.read(b)!=-1){
String s = new String(b);
System.out.print(s);
Thread.sleep(100);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
2.编写程序,使用字符输入、输出流读取文件,将一段文字加密后存入文件,然后再读取,并将加密前与加密后的文件输出。
import java.io.*;
public class Example {
public static void main(String[] args) {
char a[] = "今天10点出发".toCharArray();
int n = 0;
try {
File out = new File("word.txt");
for (int i = 0; i < a.length; i++) {
a[i] = (char) (a[i] ^ 'R');
}
FileWriter fw = new FileWriter(out);
fw.write(a, 0, a.length);
fw.close();
FileReader fr = new FileReader(out);
char tom[] = new char[10];
System.out.println("加密后:");
while ((n = fr.read(tom, 0, 10)) != -1) {
String s = new String(tom, 0, n);
System.out.println(s);
}
fr.close();
fr = new FileReader(out);
System.out.println("明文:");
while ((n = fr.read(tom, 0, 10)) != -1) {
for (int j = 0; j < n; j++) {
tom[j] = (char) (tom[j] ^ 'R');
}
String str = new String(tom, 0, n);
System.out.println(str);
}
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.编写程序,实现当用户输入姓名和密码时,将每一个姓名和密码加在文件中,如果用户输入done,就结束程序。
import java.io.*;
public class Example {
static final int lineLength = 81;
public static void main(String[] args) {
FileOutputStream fos;
byte[] phone = new byte[lineLength];
byte[] name = new byte[lineLength];
try {
fos = new FileOutputStream("word.txt");
while (true) {
System.err.println("请输入一个名字:");
if ("done".equalsIgnoreCase(new String(name, 0, 0, 4))) {
System.out.println("录入完毕");
break;
}
System.err.println("请输入电话号:");
readLine(phone);
for (int i = 0; phone[i] != 0; i++) {
fos.write(phone[i]);
}
fos.write(',');
for (int j = 0; name[j] != 0; j++) {
fos.write(name[j]);
}
fos.write('\n');
System.out.println("信息已经写入文件");
}
fos.close();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
private static void readLine(byte[] name) throws IOException {
int b = 0, i = 0;
while ((i < (lineLength - 1)) && (b = System.in.read()) != '\n') {
name[i++] = (byte) b;
}
name[i] = (byte) 0;
}
}