JAVA笔记–I/O
一、流
流是一组有序的数据序列,根据操作的类型,可以分为输入流和输出流两种。
输入流分为字节流InputStream和字符流Reader。
输出流分为字节流OutputStream和字符流Writer。
二、File类
1、文件的创建于删除
a.New File(String path_name);//new File(“d:/1.txt”);
b.New File(String parent, String child);//new File(“d:/”, “1.txt”);
创建文件:
File p_file = NULL;
p_file.createNewFile();
package javaBase;
import java.io.File;
import java.io.IOException;
public class FileOpen {
public static void main(String[] args)
{
File p_file = new File("F:/Ja/zach/0527/1.txt");
if(p_file.exists()){
System.out.println("file alreadt exist.");
} else {
System.out.println("file not exist,create it.");
try {
p_file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(p_file.exists()){
System.out.println("create file successful");
}
}
}
}
2、文件输入流FileInputStream和文件输出流FileOutputSteam。
字节流
FileInputStream 读文件
FileOutputSteam 写文件
class FileByteSteam{
public static void run() throws IOException
{
File p_file = new File("F:/Ja/zach/0527/1.txt");
if(!p_file.exists()){
System.out.println("file not exist.");
}
FileOutputStream f_out = new FileOutputStream(p_file);
String context = "我是谁,我在哪?";
f_out.write(context.getBytes());
f_out.close();
byte[] buf_read = new byte[1024];
FileInputStream f_in = new FileInputStream(p_file);
int length = f_in.read(buf_read);
System.out.println(new String(buf_read,0,length));
f_in.close();
}
}
字符流
FileReader 读文件
FileWrite 写文件
class FileCharStream{
public static void run() throws IOException
{
File p_file = new File("F:/Ja/zach/0527/1.txt");
if(!p_file.exists()){
System.out.println("file not exist.");
}
FileWriter fw = new FileWriter(p_file);
String context = "我是中国人,我在上海。";
fw.write(context);
fw.close();
char read_buf[] = new char[1024];
FileReader fr = new FileReader(p_file);
fr.read(read_buf);
System.out.println(new String(read_buf));
fr.close();
}
}
数据输入输出流
DataInputStream 数据输入流
DataOutputStream 数据输出流
public class DataStream {
public static void main(String[] args) throws IOException
{
FileOutputStream fout = new FileOutputStream("F:/Ja/zach/0527/1.txt");
DataOutputStream d_fout = new DataOutputStream(fout);
d_fout.writeUTF("我要成功。");
d_fout.writeChars("我必须成功。");
d_fout.close();
FileInputStream fin = new FileInputStream("F:/Ja/zach/0527/1.txt");
DataInputStream d_fin = new DataInputStream(fin);
System.out.println(d_fin.readUTF());
d_fin.close();
}
}
ZIP压缩输入输出流
ZipInputStream 解压缩
ZipOutputStream 压缩