I/O操作(文中例子皆来自Java从入门到精通第三版内容)
文件的创建和删除
package com.lhy;
import java.io.File;
public class FileTest {
public static void main(String[] args){
File file = new File("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\world.txt");
if (file.exists()){
file.delete();
System.out.println("文件已删除");
}else {
try {
file.createNewFile();
System.out.println("文件已创建");
}catch (Exception e){
e.printStackTrace();
}
}
}
}
方法 | 返回值 | 说明 |
---|---|---|
getname() | String | 获取文件名 |
canRead() | boolean | 判断文件是否为可读的 |
canWrite() | boolean | 判断文件是否可被写入 |
exits() | boolean | 判断文件是否存在 |
length() | long | 获取文件的长度(以字节为单位) |
getAbsolutePath() | String | 获取文件的绝对路径 |
getParent() | String | 获取文件的父路径 |
isFile() | boolean | 判断文件是否存在 |
isDirectory | boolean | 判断文件是否为一个目录 |
isHidden() | boolean | 判断文件是否为隐藏文件 |
lastModified() | long | 获取文件最后修改时间 |
代码示范
package com.lhy;
import java.io.File;
//file类的一些常用方法实例
public class FileTesst1 {
public static void main(String[] args){
File file=new File("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\world.txt");
if (file.exists()){
String name = file.getName();
long length = file.length();
boolean hidden = file.isHidden();
System.out.println("文件名称:"+name);
System.out.println("文件长度:"+length);
System.out.println("该文件是隐藏文件吗?"+hidden);
}else {
System.out.println("该文件不存在");
}
}
}
FileInputStream和FileOutputStream的用法
FileInputStream和FileOutputStream类都是用来操作磁盘文件的
代码示范
package com.lhy;
import java.io.*;
//FileInputStream和FileOutputStream的用法
public class FileTest2 {
public static void main(String[] args) throws IOException {
File file=new File("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\world.txt");
try {
FileOutputStream outputStream=new FileOutputStream(file);
byte[] buy ="我有一只小毛驴,我从来都不骑。".getBytes();
outputStream.write(buy);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileInputStream in = new FileInputStream(file);
byte[] byt =new byte[1024];
int len=in.read(byt);
System.out.println("文件中的信息是:"+new String(byt,0,len));
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileReader和FileWriter类
使用FileOutputStream类向文件写入数据与使用FileInputStream类从文件中读取数据都
存在一点不足,即这两个类都只提供了对字节或字节数组的的读取方法。由于汉字在文件中
占用两个字节,如果使用字节流,读取不好可能容易出现乱码现象,此时采用字符流Reader或
Writer类即可避免这种现象。
FileReader流顺序地读取文件,只要不关闭流,每次调用read()方法就顺序地读取源中其余的内容,
知道源的末尾或流被关闭
代码示例
package com.lhy;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class FileTest3 extends JFrame {
private static final long serialVersionUID=1L;
private JScrollPane scrollPane;
private JPanel jContentPane=null;
private JTextArea jTextArea=null;
private JPanel controlPanel=null;
private JButton openButton=null;
private JButton closeButton=null;
private JTextArea getJTextArea() {
if (jTextArea == null) {
jTextArea = new JTextArea();
}
return jTextArea;
}
private JPanel getControlPanel() {
if (controlPanel == null) {
FlowLayout flowLayout = new FlowLayout();
flowLayout.setVgap(1);
controlPanel = new JPanel();
controlPanel.setLayout(flowLayout);
controlPanel.add(getOpenButton(), null);
controlPanel.add(getCloseButton(), null);
}
return controlPanel;
}
private JButton getOpenButton(){
if (openButton==null){
openButton=new JButton();
openButton.setText("写入文件");
openButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File file=new File("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\world.txt");
try {
FileWriter out=new FileWriter(file);
String s=jTextArea.getText();
out.write(s);
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
return openButton;
}
private JButton getCloseButton(){
if (closeButton==null){
closeButton=new JButton();
closeButton.setText("读取文件");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File file=new File("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\world.txt");
try {
FileReader in=new FileReader(file);
char[] bty=new char[1024];
int len=in.read(bty);
jTextArea.setText(new String(bty,0,len));
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
return closeButton;
}
public FileTest3(){
super();
initialize();
}
private void initialize() {
this.setSize(300,200);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane==null){
jContentPane=new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getScrollPane(),BorderLayout.CENTER);
jContentPane.add(getControlPanel(),BorderLayout.SOUTH);
}
return jContentPane;
}
public static void main(String[] args){
FileTest3 thisClass=new FileTest3();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
protected JScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new JScrollPane();
scrollPane.setViewportView(getJTextArea());
}
return scrollPane;
}
}
##带缓存的输入/输出流
缓存时I/O的一种性能优化。缓存流为I/O流增加了内存缓存区。使得在流上执行skip(),mark()和reset()
方法都成为可能
BufferedReader类常用的方法
方法名 | 作用 |
---|---|
read() | 读取单个字符 |
readLine() | 读取一个文本行,并将其返回为字符串。若无数据可读,则返回null |
write(String s,int off,int len) | 写入字符串的某一部分 |
flush() | 刷新该流的缓存 |
newLine() | 写入一个行分隔符 |
代码示例
package com.lhy;
import java.io.*;
//带缓存的输入/输出流
public class FileTest4 {
public static void main(String[] args) {
String[] content = {"永远相信自己的道", "最近好吗?", "常联系"};
File file = new File("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\world.txt");
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bufw = new BufferedWriter(fw);
for (String x : content) {
bufw.write(x);
bufw.newLine();
}
bufw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader fr=new FileReader(file);
BufferedReader bufr=new BufferedReader(fr);
String s=null;
int i =0;
while ((s=bufr.readLine())!=null){
i++;
System.out.println("第"+i+"行:"+s);
}
bufr.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据输入/输出流
数据输入/输出流(DataInputStream和DataOutputStream类)允许程序以与机器无关的方式从底层输入流中读取基本Java数据类型。也就是
说,当读取一个数据时,不必再关心再关心这个数据应当是哪种字符。
代码示例
package com.lhy;
import java.io.*;
public class FileTest5 {
public static void main(String[] args){
try {
FileOutputStream fs=new FileOutputStream("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\word.txt");
DataOutputStream dss=new DataOutputStream(fs);
dss.writeUTF("使用writeUTF()方法写入数据");
dss.writeChars("使用writeChars()方法写入数据");
dss.writeBytes("使用writeBytes()方法写入数据");
dss.close();
FileInputStream fis=new FileInputStream("D:\\javaprojects\\HelloWorld\\src\\com\\lhy\\word.txt");
DataInputStream dis=new DataInputStream(fis);
System.out.println(dis.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
}
}
ZIP压缩输入/输出流
package com.lhy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
//压缩文件ZipOutputStream类对象可将文件压缩为zip文件
public class FileTest6 { // 创建类
private void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); // 创建ZipOutputStream类对象
zip(out, inputFile, ""); // 调用方法
System.out.println("压缩中…"); // 输出信息
out.close(); // 将流关闭
}
private void zip(ZipOutputStream out, File f, String base) throws Exception { // 方法重载
if (f.isDirectory()) { // 测试此抽象路径名表示的文件是否是一个目录
File[] fl = f.listFiles(); // 获取路径数组
out.putNextEntry(new ZipEntry(base + "/")); // 写入此目录的entry
base = base.length() == 0 ? "" : base + "/"; // 判断参数是否为空
for (File file : fl) { // 循环遍历数组中文件
zip(out, file, base + file);
}
} else {
out.putNextEntry(new ZipEntry(base)); // 创建新的进入点
// 创建FileInputStream对象
FileInputStream in = new FileInputStream(f);
int b; // 定义int型变量
System.out.println(base);
while ((b = in.read()) != -1) { // 如果没有到达流的尾部
out.write(b); // 将字节写入当前ZIP条目
}
in.close(); // 关闭流
}
}
public static void main(String[] temp) { // 主方法
FileTest6 book = new FileTest6(); // 创建本例对象
try {
// 调用方法,参数为压缩后文件与要压缩文件
book.zip("hello.zip", new File("D:/javaprojects/HelloWorld/src/com/lhy"));
System.out.println("压缩完成"); // 输出信息
} catch (Exception ex) {
ex.printStackTrace();
}
}
}