日期:2014-05-20  浏览次数:20860 次

输入输出问题,高分,只给有价值的回答,谢谢
课程设计写了个餐卡的管理系统,但是不知道怎么存储学生餐卡的信息,具体应实现程序关闭后再次打开还能继续信息的处理,新建的时候卡号也能继续加(开始是从201000000开始加,希望打开后不再从初始值开始,不知道说明白没~~~~),就不要说数据库了,因为没学,时间紧张也不可能学了,就用输入输出流,,谢谢

------解决方案--------------------
========================写信息的类=====================================
package com.test;

import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 将内容追加到文件尾部
 */
public class AppendToFile {

/**
* A方法追加文件:使用RandomAccessFile

* @param fileName
* 文件名
* @param content
* 追加的内容
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* B方法追加文件:使用FileWriter

* @param fileName
* @param content
*/
public static void appendMethodB(String fileName, String content) {
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);

writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String fileName = "src/com/test/file1.txt";
String content = "new append!";
// 按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. n\n");
// 显示文件内容
ReadFromFile.readFileByLines(fileName);
// 按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. n\n");
// 显示文件内容
ReadFromFile.readFileByLines(fileName);
}
}


================================显示信息的类==========================


package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;

/**
 * 
 * 1、按字节读取文件内容 
 * 2、按字符读取文件内容 
 * 3、按行读取文件内容 
 * 4、随机读取文件内容
 * 
 * @author leadron
 * 
 */
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。

* @param fileName
* 文件的名
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {