RandomAccessFile:
按照指针读取
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; /** * RandomAccessFile 使用范例 * */ public class RandomAccessFileDemo { public static void main(String[] args) throws Exception { Person[] persons = new Person[] { new Person("one", 25, true), new Person("two", 26, false), new Person("three", 27, true), new Person("four", 28, false) }; write(persons); Person p = read(2);//读取第三个 System.out.println(p); } private static List<Long> pointer; private static void write(Person[] persons) throws Exception { File _file = new File("data/store.dat"); if (!_file.exists()) { File dir = _file.getParentFile(); dir.mkdir(); } RandomAccessFile file = new RandomAccessFile("data/store.dat", "rw"); pointer = new ArrayList<Long>(); for (Person p : persons) { pointer.add(file.getFilePointer());//指针 每个对象头指针放在arraylist中 file.writeUTF(p.name); System.out.println("name: " + file.getFilePointer()); file.writeInt(p.age); System.out.println("age: " + file.getFilePointer()); file.writeBoolean(p.sex); System.out.println("sex: " + file.getFilePointer()); } file.close(); } private static Person read(int i) throws Exception { RandomAccessFile file = new RandomAccessFile("data/store.dat", "rw"); Long l = pointer.get(i); file.skipBytes(Integer.parseInt(String.valueOf(l))); //file.seek(l); Person p = new Person(); p.name=file.readUTF();//顺序一定要一致 p.age=file.readInt(); p.sex=file.readBoolean(); file.close();//不关闭 读入不会错 写入会报错啊 return p; } } class Person { String name; int age; boolean sex; public Person() { } public Person(String name, int age, boolean sex) { this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { // TODO Auto-generated method stub return "Person [age=" + age + ", name=" + name + ", sex=" + sex + "]"; } }
1.字符流
Reader:
1.File文件关联
2.创建Reader阅读器
3.reader方法工作 读出全部文件
4.close阅读器和流
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; public class ReaderDemo { public static void main(String[] args) throws Exception { // 编码 // byte[] byets; // String str=new String(byets, "utf-8"); // byets[] bytes=str.getBytes("utf-8"); File file = new File("src/ReaderDemo.java");// 1文件关联 Reader reader = new FileReader(file);// 2创建阅读器 // int i = reader.read();// 读取单个字符 // System.out.println(i); int i; char[] array = new char[200]; // //3reader方法工作 读出全部文件 // while (true) { // i = reader.read(array); // if (i == -1) { // break; // } // for (int j = 0; j < i; j++) { // System.out.print(array[j]); // } // } // 读出全部文件 int len = -1; while ((len = reader.read(array, 0, array.length)) != -1) { for (int j = 0; j < len; j++) { System.out.print(array[j]); } } reader.close();// 4关闭阅读器 } }
Write:
1.File文件关联
2.创建Write编写器
3.write方法工作 写入文件
4.flush缓存和close编写器,流
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.Scanner; public class WriteDemo { public static void main(String[] args) throws Exception { System.out.println("需要创建什么文件:"); Scanner scanner = new Scanner(System.in); String filename = scanner.nextLine(); // 1文件关联 File file = new File(filename); // 2创建编写器 Writer writer = new FileWriter(file); System.out.println("输入你需要的内容:"); while (true) { String content = scanner.nextLine(); if (content.length() == 0) { break; } // 3write方法工作 文件写入 writer.write(content); writer.write("\r\n"); } writer.flush(); // 4关闭编写器 writer.close(); } }
文件,内容复制
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; import java.io.Writer; //文件复制类 public class CopyContentDemo { public static void main(String[] args) throws Exception { //内容复制 File inputfile = new File("src/CopyContentDemo.java"); File outfile = new File("outfile.java"); Reader reader = new FileReader(inputfile); Writer writer = new FileWriter(outfile); // int i; // char[] carray = new char[200]; // while (true) { // i = reader.read(carray); // if (i == -1) { // break; // } // for (int j = 0; j < i; j++) { // writer.write(carray[j]); // } // } int len = -1; char[] date = new char[200]; while ((len = reader.read(date, 0, date.length)) != -1) { writer.write(date, 0, len); } System.out.println("数据复制成功!"); reader.close(); writer.flush(); writer.close(); } }
LineNumberReader:
读取行号的包装流
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.LineNumberReader; //读取行号的包装流 public class LineNumberReaderDemo { public static void main(String[] args) throws Exception { File file = new File("src/LineNumberReaderDemo.java"); // 包装流读取全文件 LineNumberReader reader = new LineNumberReader(new FileReader(file)); String s; while ((s = reader.readLine()) != null) { System.out.print(reader.getLineNumber() + ": "); System.out.println(s); } } }
2.字节流
fileinputstream对应的byte[]
inputstreamreader对应的char[]
都是整形int时候为-1判断
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class CharsetDemo { // 字节流练习 public static void main(String[] args) throws Exception { // TODO Auto-generated method stub error("txt/a.txt"); System.out.println("--------------------------------------"); right("txt/a.txt", "GBK"); } public static void error(String filepath) throws Exception { File file = new File(filepath); // //1.BufferedReader包装流实现 // BufferedReader reader = new BufferedReader(new FileReader(file)); // String s; // while ((s = reader.readLine()) != null) { // System.out.println(s); // } // //2.BufferedInputStream包装流实现 // BufferedInputStream bis=new BufferedInputStream(new // FileInputStream(file)); // int i; // while ((i=bis.read())!=-1) { // System.out.print((char)i); // } // 3.FileInputStream字节流实现 FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = -1; while ((len = fis.read(bytes, 0, bytes.length)) != -1) { // String s=new String(bytes); String s = new String(bytes, "UTF-8");// 解决乱码 System.out.println(s); } } public static void right(String filepath, String charset) throws Exception { File file = new File(filepath); InputStreamReader isr = new InputStreamReader(new BufferedInputStream( new FileInputStream(file)), charset); char[] array = new char[50]; int i = -1; while ((i = isr.read(array)) != -1) { for (int j = 0; j < i; j++) { System.out.print(array[j]); } } } }
3.包装流
简单包装流读写文件
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; public class BufferedDemo { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // 系统文件目录 String dir = System.getProperty("user.dir"); File infile = new File(dir + "/src/kbstream/BufferedDemo.java"); File outfile = new File("txt/out.txt"); BufferedReader in = new BufferedReader(new FileReader(infile)); BufferedWriter out = new BufferedWriter(new FileWriter(outfile)); String line; while ((line = in.readLine()) != null) { out.write(line); out.write("\r\n"); } in.close(); out.flush(); out.close(); } }
DataStream:
按照特定的数据类型读写数据
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DataStreamDemo { final public static String FILENAME = "txt/data.dat"; // 按照特定的数据类型读写数据 public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Person[] persons = { new Person("zhang", 40, true), new Person("li", 14, false) }; WriteToFile(persons); // persons = ReaderFromFile(); // for (Person p : persons) { // System.out.println(p); // } // 输出集合内容 System.out.println(Arrays.toString(persons)); } private static void WriteToFile(Person[] persons) throws Exception { File file = new File(FILENAME); //两次用了包装流 就为了放缓存区 性能高效 DataOutputStream dos = new DataOutputStream(new BufferedOutputStream( new FileOutputStream(file))); for (Person p : persons) { dos.writeUTF(p.name); dos.writeInt(p.age); dos.writeBoolean(p.sex); } dos.flush(); dos.close(); } private static Person[] ReaderFromFile() throws Exception { File file = new File(FILENAME); DataInputStream dis = new DataInputStream(new BufferedInputStream( new FileInputStream(file))); List<Person> list = new ArrayList<Person>(); try { while (true) { Person p = new Person(); p.name = dis.readUTF(); p.age = dis.readInt(); p.sex = dis.readBoolean(); list.add(p); } } catch (Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); } dis.close(); // 集合转换成数组 参数 new Person[0]只是为了确定数组类型 return list.toArray(new Person[0]); } } class Person { String name; int age; boolean sex; public Person() { // TODO Auto-generated constructor stub } public Person(String name, int age, boolean sex) { this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { // TODO Auto-generated method stub return "Person: name: " + name + " age: " + age + " sex: " + sex; } }
ObjectStream:
按照对象读写数据
一定要实现对象的序列化
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ObjectStreamDemo { final public static String FILENAME = "txt/object.dat"; // objectstream 一定要实现序列化 public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Human[] humans = { new Human("zhang", 14, true), new Human("li", 40, false) }; writeToFile(humans); humans = readFromFile(); System.out.println(Arrays.toString(humans)); } public static void writeToFile(Human[] humans) throws Exception { File file = new File(FILENAME); ObjectOutputStream oos = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(file))); for (Human h : humans) { oos.writeObject(h); } oos.flush(); oos.close(); } public static Human[] readFromFile() throws Exception { File file = new File(FILENAME); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream( new FileInputStream(file))); List<Human> list = new ArrayList<Human>(); try { while (true) { //一个一个对象读取的 也可以判断是否为null再list添加的 Human human = (Human) ois.readObject(); list.add(human); } } catch (Exception e) { // TODO Auto-generated catch block } ois.close(); return list.toArray(new Human[0]); } } class Human implements Serializable { /** * */ private static final long serialVersionUID = -6916114420631083299L; String name; int age; boolean sex; public Human() { // TODO Auto-generated constructor stub } public Human(String name, int age, boolean sex) { this.name = name; this.age = age; this.sex = sex; } @Override public String toString() { // TODO Auto-generated method stub return "Human: name: " + name + " age: " + age + " sex: " + sex; } }
实现音频视频等二进制文件复制
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileCopyDemo { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub String dir = System.getProperty("user.dir"); File infile = new File(dir + "/txt/love你.mp3"); String outfilepath = "D:/txt/love你.mp3"; createFileAndDir(outfilepath); File outfile = new File(outfilepath); // 因为针对二进制文件 所以要用字节流 // 1.效率低 // FileInputStream in=new FileInputStream(infile); // FileOutputStream out=new FileOutputStream(outfile); // 2.包装流 效率高 BufferedInputStream in = new BufferedInputStream(new FileInputStream( infile)); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(outfile)); byte[] c = new byte[4096]; int len = -1; while ((len = in.read(c, 0, c.length)) != -1) { out.write(c, 0, len); } // 用字符流只能copy大小 "内容"无法完成编码 mp3放不出来 // BufferedReader in = new BufferedReader(new FileReader(infile)); // BufferedWriter out = new BufferedWriter(new FileWriter(outfile)); // String line; // while ((line = in.readLine()) != null) { // out.write(line); // out.write("\r\n"); // } System.out.println("copy ok!"); in.close(); out.flush(); out.close(); } private static void createFileAndDir(String filepath) throws Exception { File file = new File(filepath); if (file.exists()) { return; } File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } file.createNewFile(); } }
时间: 2024-11-09 00:43:51