字符流
实例140 按顺序创建文件
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterTest {
public static void main(String[] args) {
FileWriter fw;
try {
fw = new FileWriter("E:/TestApplet.java"); // 创建字符输出流对象
BufferedWriter bf = new BufferedWriter(fw); // 创建缓冲字符输出流对象
for (int i = 0; i < 10; i++) { // 将字符串写入文件
bf.write("Line" + i);
}
bf.close(); // 关闭缓冲字符输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
实例141 按顺序读取文件
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderTest {
public static void main(String[] args) {
FileReader fr;
try {
fr = new FileReader("E:/TestApplet.java"); // 创建文件字符输出流对象
BufferedReader br = new BufferedReader(fr); // 创建缓冲字符输出流对象
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
实例142 追加文件内容
package Chapter07.Characters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
public class CharactersDemo_03 {
// 使用RandomAccessFile实现文件的追加,其中:fileName表示文件名;content表示要追加的内容
public static void appendMethod_one(String fileName, String content) {
try {
// 按读写方式创建一个随机访问文件流
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
long fileLength = raf.length();// 获取文件的长度即字节数
// 将写文件指针移到文件尾。
raf.seek(fileLength);
// 按字节的形式将内容写到随机访问文件流中
raf.writeBytes(content);
// 关闭流
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 使用FileWriter实现文件的追加,其中:fileName表示文件名;content表示要追加的内容
public static void appendMethod_two(String fileName, String content) {
try {
// 创建一个FileWriter对象,其中boolean型参数则表示是否以追加形式写文件
FileWriter fw = new FileWriter(fileName, true);
// 追加内容
fw.write(content);
// 关闭文件输出流
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void showFileContent(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println(line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
String fileName = "D:/temp/append.txt";
String content = "Successful operation!";
System.out.println(fileName + "文件的内容如下:");
CharactersDemo_03.showFileContent(fileName); // 显示文件内容
// 按RandomAccessFile的形式追加文件
System.out.println("\n按RandomAccessFile的形式追加文件后的内容如下:");
CharactersDemo_03.appendMethod_one(fileName, content);
CharactersDemo_03.appendMethod_one(fileName, "\n Game is Over! \n");
CharactersDemo_03.showFileContent(fileName); // 显示文件内容
// 按FileWriter的形式追加文件
System.out.println("\n按FileWriter的形式追加文件后的内容如下:");
CharactersDemo_03.appendMethod_two(fileName, content);
CharactersDemo_03.appendMethod_two(fileName, "\n Game is Over! \n");
CharactersDemo_03.showFileContent(fileName); // 显示文件内容
}
}
实例143 只显示文件中指定的字符
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class StringTest {
public static void main(String[] args) throws IOException {
try {
RandomAccessFile rf = new RandomAccessFile("D:\\test.txt", "r");
// 创建一个RandomAccessFile类对象
long count = Long.valueOf(args[0]).longValue();
// 由命令行参数传入一个数字count,表示显示文件中最后的count个字符
long pos = rf.length();// 返回文件的长度
pos -= count;
if (pos < 0)
pos = 0;
rf.seek(pos);// 将指针移动到文件尾
while (true) {
try {
byte b = rf.readByte();// 读取一个字节
System.out.print((char) b);// 将读取的字节转换成字符输出
} catch (EOFException e) {
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
实例144 读取jar包文件
package Chapter07.Characters;
import java.awt.geom.Area;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class CharactersDemo_05 {
// javaClass表示类文件;filepath表示文件的相对路径
public static void readJar_URL(Class javaClass, String filepath) {
URL url = javaClass.getResource(filepath);// 获取定位资源URL对象
System.out.println("资源的URL: " + url);
try {
InputStream stream = url.openStream();// 打开fileURL对应的文件流
BufferedReader bufferedreader = new BufferedReader(// 创建一个缓冲字符输入流
new InputStreamReader(stream));
String str;
while ((str = bufferedreader.readLine()) != null) {// 从缓冲字符输入流中按行读取信息
System.out.println(str);
}
stream.close();// 关闭流
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
// 读Jar包中的资源信息,其中:javaClass表示类文件;filepath表示文件的相对路径
public static void readJar_stream(Class javaClass, String filepath) {
InputStream stream = javaClass.getResourceAsStream(filepath);// 获取该资源输入流的引用
if (stream != null) {
// 创建一个缓冲字符输入流
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(stream));
String str;
try {
// 从缓冲字符输入流中按行读取信息
while ((str = bufferedreader.readLine()) != null) {
System.out.println(str);
}
stream.close();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("以该class文件的位置为准,以URL的方式读取Jar包信息的内容如下:");
Class javaClass = aa.class;//在该文件的目录下要存在aa.class文件
String filePath = "config0.conf";//filePath的值是要读取的jar包名称
CharactersDemo_05.readJar_URL(javaClass, filePath);
System.out.println();
System.out.println("以该class文件的位置为准,以直接获取资源输入流的引用的方式读取Jar包信息的内容如下:");
filePath = "bdc/config1.conf";//filePath的值是要读取的jar包名称
CharactersDemo_05.readJar_stream(javaClass, filePath);
System.out.println();
System.out.println("以该jar文件的位置为准,以URL的方式读取Jar包信息的内容如下::");
filePath = "/jarTest/abc/bdc/config1.conf";//filePath的值是要读取的jar包名称
CharactersDemo_05.readJar_URL(javaClass, filePath);
}
}
实例145 文件的加密/解密操作
package Chapter07.Characters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
public class CharactersDemo_06 {
private File file; // 存储文件对象信息
byte[] buf; // 缓冲区,存储文件中的所有数据
RandomAccessFile raf;
public CharactersDemo_06(String filename) {
file = new File(filename);
buf = new byte[(int) file.length()];
}
// 按照读写方式打开文件
public void open() throws FileNotFoundException {
raf = new RandomAccessFile(file, "rw");
}
// 关闭文件
public void close() throws IOException {
raf.close();
}
// 对文件进行加密或解密
public void password() throws IOException {
raf.read(buf);// 将文件内容读入到缓冲区中
for (int i = 0; i < buf.length; i++)
buf[i] = (byte) (~buf[i]);// 将缓冲区中的内容按位取反
raf.seek(0);// 将文件指针定位到文件头部
raf.write(buf);// 将缓冲区中的内容写入到文件中
}
// 显示文件的内容
public static void showFileContent(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println(tempString);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String argv[]) {
CharactersDemo_06 oa;
if (argv.length < 1) {
System.out.println("你需要指定待加密的文件名称!");
return;
}
// 下面利用encrypt对象oa对由命令行参数指定的文件进行加密处理
oa = new CharactersDemo_06(argv[0]);
try {
oa.open();// 打开文件
oa.password();// 先对指定的文件加密
System.out.println("文件加密成功!加密后的文件内容如下:");
CharactersDemo_06.showFileContent(argv[0]);// 显示加密后文件的内容
oa.password();// 再对已经加密的文件解密
oa.close();// 关闭文件
System.out.println("\n文件解密成功!解密后的文件内容如下:");
CharactersDemo_06.showFileContent(argv[0]);// 显示解密后文件的内容
} catch (FileNotFoundException e) {
System.out.println("打不开指定文件:" + argv[0]);
} catch (IOException e) {
System.out.println("文件读写出错:" + argv[0]);
}
}
}
实例146 复制图片
package Chapter07.Characters;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class StreamDemo extends JFrame {
private JPanel j;
private BorderLayout bl = new BorderLayout();
// 添加组件
private JPanel j1 = new JPanel();
private JScrollPane js = new JScrollPane();
private JTextArea jta = new JTextArea();
private JLabel jl1 = new JLabel();
private JLabel jl2 = new JLabel();
private JButton jb = new JButton();
private GridLayout gl = new GridLayout();
private JTextField jtf1 = new JTextField();
private JTextField jtf2 = new JTextField();
// 定义文件输入输出流
File f = null;
File ff = null;
FileInputStream fis = null;
FileOutputStream fos = null;
DataInputStream dis = null;
DataOutputStream dos = null;
private void jbInit() {
// 设置各组件及窗口属性,窗口的布局,并在窗口中添加各组件
j = (JPanel) this.getContentPane();
j.setLayout(bl);
this.setSize(new Dimension(395, 195));
this.setTitle("复制图片操作");
jb.setText("开始");
jb.addActionListener(new ActionListener() {// 添加事件监听器
public void actionPerformed(ActionEvent e) {
try {
jb_actionPerformed(e);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
jl1.setMaximumSize(new Dimension(50, 18));
jl1.setText("源文件:");
jl2.setText("目标文件");
j1.setLayout(gl);
gl.setColumns(2);
gl.setRows(2);
j.add(j1, BorderLayout.NORTH);
j1.add(jl1, null);
j1.add(jtf1, null);
j1.add(jl2, null);
j1.add(jtf2, null);
j.add(js, BorderLayout.CENTER);
js.getViewport().add(jta, null);
j.add(jb, BorderLayout.SOUTH);
this.setVisible(true);
}
void jb_actionPerformed(ActionEvent e) throws Exception {
final int BufferSize = 1024;// 定义缓冲区大小
byte[] b = new byte[BufferSize];// 创建缓冲区
f = new File(this.jtf1.getText());
ff = new File(this.jtf2.getText());
if (!ff.exists())
try {
ff.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 打开文件的输入输出流
fis = new FileInputStream(f);
fos = new FileOutputStream(ff);
// 将数据输入输出流与文件输入输出流链接
dis = new DataInputStream(fis);
dos = new DataOutputStream(fos);
// 清空,并显示源文件和目标文件信息
this.jta.setText("");
this.jta.append("读取文件:" + f.getAbsolutePath() + "\n");
this.jta.append("写入文件:" + ff.getAbsolutePath() + "\n");
// 利用缓冲区读写文件
int bytes;
while ((bytes = dis.read(b, 0, BufferSize)) != -1) {
dos.write(b, 0, bytes);
this.jta.append("读取 " + bytes + "B" + " 写入 " + bytes + "B" + "\n");
}
// 显示读写完成
this.jta.append("完成");
// 关闭流
dis.close();
dos.close();
}
public static void main(String[] args) {
new StreamDemo().jbInit();
}
}
实例147 随机读写Java类文件
package Chapter07.Characters;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class CharactersDemo_07 {
public static void RandomToWrite(File file) {
Student[] students = new Student[4]; // 创建Student数组
// 初始化Student数组
students[0] = new Student("优秀", "90");
students[1] = new Student("优良", "80");
students[2] = new Student("良好", "70");
students[3] = new Student("及格", "60");
RandomAccessFile randomAccessFile = null; // 创建RandomAccessFile对象
try {
randomAccessFile = new RandomAccessFile(file, "rw"); // 创建一个可以支持读写状态的RandomAccessFile对象
} catch (FileNotFoundException e1) { // 捕获异常
System.out.println("文件没有找到" + e1.getMessage()); // 输出异常信息
}
try {
for (int i = 0; i < students.length; i++) // for遍历students数组
{
randomAccessFile.writeChars(students[i].getLevel()); // 向文件中写入评分等级
randomAccessFile.writeChars(students[i].getScore()); // 向文件中写入分数
}
randomAccessFile.close(); // 关闭randomAccessFile
} catch (IOException e1) { // 捕获异常
e1.printStackTrace(); // 输出异常信息
}
}
private static String readName(RandomAccessFile randomAccessfile)
throws IOException {
char[] name = new char[5]; // 创建char类型数组
for (int i = 0; i < name.length; i++) {
name[i] = randomAccessfile.readChar(); // 读取字符
}
return new String(name);
}
public static Student[] RandomToRead(File file) throws Exception {
RandomAccessFile randomAccessFile; // 创建RandomAccessFile实例
randomAccessFile = new RandomAccessFile(file, "r"); // 初始化randomAccessFile对象
int num = (int) randomAccessFile.length() / Student.size(); // 返回Student类的占用空间大小
Student[] student = new Student[num]; // 创建Student数组student
for (int i = 0; i < num; i++) {
randomAccessFile.seek((i) * Student.size());
// 使用对应的read方法读出数据。
student[i] = new Student(readName(randomAccessFile),
readName(randomAccessFile));
}
randomAccessFile.close(); // randomAccessFile关闭
return student; // 返回数组
}
public static void main(String[] args) throws Exception {
// 创建,并初始文件名称
String filename = "D:/temp/1.txt";
File file = new File(filename); // 创建并初始File对象file
RandomToWrite(file); // 调用RandomWriteFile方法
Student[] student = RandomToRead(file); // 返回文件中保存的student数组
// 使用for,遍历student数组
System.out.println(filename + "的内容如下:");
for (int i = 0; i < student.length; i++) {
System.out.println("Level=" + student[i].getLevel() + "|Score="
+ student[i].getScore());
}
}
}
class Student {
String level; // 评分级别
String score; // 分数
final static int SIZE = 8; // 创建,并初始化静态域LEN
public Student(String level, String score) {
if (level.length() > SIZE) {
level = level.substring(0, 8); // 截取字符串的子字符串
} else {
while (level.length() < SIZE)
level = level + "\u0000";
}
this.level = level; // 初始化level
this.score = score; // 初始化score
}
// 获取类占用的空间
public static int size() {
return 20;// 字符串长度是8,一个字符占用2个字节,一个整型是4个字节
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}