I/O(输入/输出)实例

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;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值