将自己看作为程序,将数据输出到文件中,称之为输出。
从文件读取数据到程序,称为输出。
JAVA流操作主要分为字节流、字符流。
字节流鼻祖:InputStream\OutpuStream
字符流鼻祖:Reader\Writer
File
1、File常用方法
package learn.javase;
import java.io.File;
/**
* File常用操作
* @author Jole
*
*/
public class FileDemo01 {
public static void main(String[] args) {
File file = new File("H://");
//此抽象路径名表示的文件或目录的名称;如果路径名的名称序列为空,则返回空字符串
System.out.println(file.getName());
//返回文件大小
System.out.println(file.length());
//返回绝对路径
System.out.println(file.getAbsolutePath());
//绝对路径名
System.out.println(file.getAbsoluteFile());
//父目录
System.out.println(file.getParentFile());
//是否存在
System.out.println(file.exists());
//是否是目录
System.out.println(file.isDirectory());
//返回路径下的文件或文件夹
System.out.println(file.list());
for(String path : file.list()) {
//获取路径
System.out.println(path);
}
//可用的文件系统根
System.out.println("listRoots:"+file.listRoots());
for(File f : file.listFiles()) {
System.out.println("111"+f);
System.out.println(f.list());
System.out.println(f.length());
System.out.println("111"+f.listRoots());
}
}
}
2、实例
遍历所有文件
package learn.javase;
import java.io.File;
/**
* 遍历文件
* @author Jole
*
*/
public class SearchFIles {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("H:\\");
findFile(file);
}
public static void findFile(File file) {
System.out.println("--"+file);
File[] array = file.listFiles();
for(File f : array) {
if(f.isDirectory()) {
findFile(f);
}else {
System.out.println(f);
}
}
}
}
3、文件过滤器
通过文件过滤器,查询所有.java文件
package learn.javase;
import java.io.File;
/**
* FileFilter文件过滤器
* @author Jole
*
*/
public class FileFilterDemo01 {
public static void main(String[] args) {
File f = new File("H:\\");
File [] filsArray =f.listFiles(new MyFilter());
for(File file : filsArray) {
System.out.println("路径: "+file+"大小: "+file.length());
}
}
}
文件过滤器实现:
package learn.javase;
import java.io.File;
import java.io.FileFilter;
/**
* 利用文件过滤器筛选文件FileFilter
* @author Jole
*
*/
public class MyFilter implements FileFilter{
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".java");
}
}
字节流
字节输出流
package learn.javase;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 字节输出流,写入文件
* @author Jole
*
*/
public class FileOutpuStream {
public static void main(String[] args) throws IOException{
FileOutputStream fos = new FileOutputStream("H://fileoutputstream.txt");
fos.write(2014);
byte[] b = {66,67,68,69};
fos.write(b);
fos.write(b,1,2);
fos.write("Hello World".getBytes());
fos.close();
}
}
File对象:
package learn.javase;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 字节输出流
* @author Jole
*
*/
public class FileOutPutStream2 {
public static void main(String[] args) throws IOException{
File f = new File("H://111.txt");
FileOutputStream fos = new FileOutputStream(f, true);
fos.write("Hello\r\n".getBytes());
fos.write("World".getBytes());
fos.close();
}
}
字节输入流
实例:利用字节输入输出流拷贝文件
package learn.javase;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 利用字节输入输出流拷贝文件
* @author Jole
*
*/
public class FileInPutStream02 {
public static void main(String[] args) {
// try {
// getLdfdas();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
getAll();
}
private static void getLdfdas() throws IOException{
FileInputStream fis = new FileInputStream("H:\\222.txt");
//创建字节数组
byte[] b = new byte[1024];
int len = 0 ;
while( (len = fis.read(b)) !=-1){
System.out.print(new String(b,0,len));
}
fis.close();
}
public static void getAll() {
FileInputStream fis = null;
try {
fis = new FileInputStream("H:\\222.txt");
byte[] b = new byte[1024];
int len = 0;
while( (len = fis.read(b)) !=-1) {
System.out.println(new String(b,0,len));
}
}catch(IOException e) {
throw new RuntimeException("读取失败,请重试");
}finally {
try {
fis.close();
}catch(IOException ex) {
throw new RuntimeException("流关闭失败");
}
}
}
}
异常处理
package learn.javase;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 输出流异常处理
* @author Jole
*
*/
public class IoTryCatch {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
File f = new File("H://222.txt");
fos = new FileOutputStream(f, true);
fos.write("Hello\r\nWorld".getBytes());
}catch(IOException e) {
System.out.println(e.getMessage());
throw new RuntimeException("写入失败,请重试");
}finally {
if(null!=fos) {
try {
fos.close();
}catch(IOException ex) {
System.out.println(ex.getMessage());
throw new RuntimeException("关闭失败");
}
}
}
}
}
实例
利用字节流拷贝文件:
package learn.javase;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* 基于输入、输出流的文件拷贝
* @author Jole
*
*/
public class CopyFIleDemo {
public static void main(String[] args) {
copyFiles();
}
public static void copyFiles() {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("H:\\1.exe");
fos = new FileOutputStream("D:\\new1.exe");
byte[] b = new byte[1024];
int len =0;
while((len=fis.read(b))!=-1) {
fos.write(b,0,len);
}
}catch(Exception e) {
System.out.println(e.getMessage());
throw new RuntimeException("复制失败");
}finally {
if(null!=fos) {
try {
fos.close();
}catch(Exception e) {
throw new RuntimeException("输出流关闭失败");
}finally {
try {
if(null!=fis) {
fis.close();
}
}catch(Exception e) {
System.out.println(e.getMessage());
throw new RuntimeException("输入流关闭失败");
}
}
}
}
}
}
字符流
字节输出流
package learn.javase;
import java.io.FileWriter;
import java.io.IOException;
/**
* 字符输出流,写文件
*/
public class FileWriteDemo01 {
public static void main(String[] args) throws IOException{
FileWriter fw = new FileWriter("H://write.txt");
char[] c = {'a','b','v','d'};
fw.write(c,1,2);
fw.flush();
fw.close();
}
}
字符输入流
package learn.javase;
import java.io.FileReader;
import java.io.IOException;
/**
* 字符输入流,读取文件
* @author Jole
*
*/
public class FileReaderDemo {
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("H:\\write.txt");
char[] c = new char[1024];
int len =0;
while((len = fr.read(c)) != -1) {
System.out.println(new String(c, 0, len));
}
fr.close();
}
}
实例
理由字符流拷贝文件:
package learn.javase;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* 利用字符输入流、字符输出流拷贝文本文件
* @author Jole
*
*/
public class CopyTxtFile {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("H:\\write.txt");
fw = new FileWriter("I:\\copytxt.txt");
char[] c = new char[1024];
int len =0;
while((len = fr.read(c)) != -1) {
fw.write(c, 0, len);
fw.flush();
}
System.out.println("文本文件复制成功");
}catch(Exception e) {
throw new RuntimeException("复制失败,请重试!");
}finally {
if(null != fw) {
try {
fw.close();
}catch(IOException e) {
throw new RuntimeException("字符输入流关闭失败!");
}finally {
if(null != fr) {
try {
fr.close();
}catch(IOException e) {
throw new RuntimeException("字符输出流关闭失败!");
}
}
}
}
}
}
}
转换流
利用转换流InputStreamReader:将字节流转成字符流
package learn.javase;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* 利用转换流InputStreamReader:将字节流转成字符流
* @author Jole
* 与字节流的区别在于可以设置写入、写出时文件的编码集
*/
public class InputStreamReaderDemo01 {
public static void main(String[] args) {
try {
myInputStreamReader();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void myInputStreamReader() throws IOException{
FileInputStream is = new FileInputStream("H:\\zz.txt");
InputStreamReader isr = new InputStreamReader(is, "GBK");
int len =0;
char[] c = new char[1024];
while((len = isr.read(c)) != -1) {
System.out.println(new String(c, 0 ,len));
}
isr.close();
}
}
缓冲流
缓冲流-字节输出流
package learn.javase;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 字节缓冲输出流
* @author Jole
*
*/
public class BufferedOutputStreamDemo01 {
public static void main(String[] args) {
try {
bufferWriter();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void bufferWriter() throws IOException{
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("H:\\c.txt"));
bos.write("Hello world".getBytes());
bos.flush();
bos.close();
}
}
缓冲流-字节输入流
package learn.javase;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* 字节缓冲输入流,读取文件
* @author Jole
*
*/
public class BufferInputStreamDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
bufferInputTxt();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void bufferInputTxt() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("H:\\c.txt"));
byte[] b = new byte[1024];
int len =0;
while((len = bis.read(b)) != -1) {
System.out.print(new String(b, 0 , len));
}
}
}
缓冲流-字符输出流
package learn.javase;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
/**
* 字符缓冲输出流,独有writeLine()换行与平台无关
* @author Jole
*
*/
public class BufferWriterDemo01 {
public static void main(String[] args) {
try {
bufferWrited();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void bufferWrited() throws IOException{
BufferedWriter bw = new BufferedWriter(new FileWriter("H:\\zxw.txt"));
bw.write("Hello World");
bw.newLine();
bw.flush();
bw.close();
}
}
缓冲输-字符输入流
package learn.javase;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* 字符缓冲输入流,独有readlin方法
* @author Jole
*
*/
public class BufferedReaderDemo02 {
public static void main(String[] args) {
try {
bufferReadered();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void bufferReadered() throws IOException{
int n=0;
BufferedReader br = new BufferedReader(new FileReader("H:\\zxw.txt"));
String len =null;
while((len = br.readLine()) != null) {
n++;
System.out.println(n+"\t"+len);
}
br.close();
}
}
对象流
序列化
利用对戏那个输入输出流,进行序列化与反序列化
package learn.javase;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 利用对戏那个输入输出流,进行序列化与反序列化
* 实现Serializable接口的目的是为了可以被序列化,
* transient关键字标记的标量 不会被序列化
* @author Jole
*
*/
public class ObjectLiu {
public static void main(String[] args) throws IOException,ClassNotFoundException{
//序列化
// objectOutputStreamInfo();
//反序列化
objectinputStreamInfo();
}
public static void objectOutputStreamInfo() throws IOException{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("H:\\z2.txt"));
Persion persion = new Persion("zhangsan",30);
oos.writeObject(persion);
oos.close();
}
public static void objectinputStreamInfo() throws IOException,ClassNotFoundException{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("H:\\z2.txt"));
Persion persion = (Persion)ois.readObject();
System.out.println(persion);
ois.close();
}
}
实现Serializable接口的目的是为了可以被序列化:
package learn.javase;
import java.io.Serializable;
/**
* 实现Serializable接口的目的是为了可以被序列化,
* transient关键字标记的标量不会被序列化
* @author Jole
*
*/
public class Persion implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2056540569585913293L;
private String name;
private transient int age;
public Persion(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Persion() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Persion [name=" + name + ", age=" + age + "]";
}
}
打印流
利用打印流复制文件:设计打印机流自动刷新(流对象才支持自动刷新,File、字符串不支持自动刷新)
package learn.javase;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 利用打印流复制文件:设计打印机流自动刷新(流对象才支持自动刷新,File、字符串不支持自动刷新)
* PrintStream\PrintWriter
* @author Jole
*
*/
public class PrintLiu {
public static void main(String[] args) throws IOException{
copyFiles();
}
public static void copyFiles() throws IOException{
BufferedReader br = new BufferedReader(new FileReader("H:\\zz.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("D:\\zz.txt"));
String len = null;
while((len = br.readLine()) != null) {
pw.println(len);
}
pw.close();
br.close();
}
}
Properties
读取Properties文件的值和写入值
package learn.javase;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
/**
* Properties的load(),store方法
* 读取Properties文件的值和写入值
* @author Jole
*
*/
public class PropertiesDemo {
public static void main(String[] args) throws IOException{
function();
}
public static void function() throws IOException{
Properties pro = new Properties();
FileInputStream fs = new FileInputStream("H:\\pro.properties");
pro.load(fs);
fs.close();
FileWriter fw = new FileWriter("H:\\1.properties");
pro.store(fw, "add");
fw.close();
System.out.println(pro);
}
}
开源工具Commons-IO
FilenameUtils
package learn.javase.utils;
import org.apache.commons.io.FilenameUtils;
/**
* Commons-io工具类 FilenameUtis常用方法
* @author Jole
*
*/
public class CommonsIODemo {
public static void main(String[] args) {
//打印后缀,没有则为空
String name = FilenameUtils.getExtension("demo.java");
System.out.println(name);
//获取文件名
String fileName = FilenameUtils.getName("H:\\z.txt");
System.out.println(fileName);
//判断后缀名
boolean Extension = FilenameUtils.isExtension("World.java", "java");
System.out.println(Extension);
}
}
FileUtils
package learn.javase.utils;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
* 利用开源工具Commons-IO中的FileUtils工具类进行文件的常规操作
* @author Jole
*
*/
public class CommonsIOFileUtils {
public static void main(String[] args) throws IOException{
//读文件
String string = FileUtils.readFileToString(new File("H:\\zz.txt"));
System.out.println(string);
//写文件
FileUtils.writeStringToFile(new File("H:\\cc.txt"), "Look ME");
//复制文件
FileUtils.copyFile(new File("H:\\z.txt"), new File("D:\\xx.txt"));
//复制文件夹
FileUtils.copyDirectoryToDirectory(new File("H:\\a"), new File("D:\\a"));
}
}
注意点
1、每种流的特有方法
2、异常的处理
3、一定要关闭流
4、哪种情况选择哪种流
评论 (0)