一、创建文本文件
package day05; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; //创建文本文件 public class Work06 { public static void main(String[] args) throws IOException { File f = new File("D:/QQQ","aaa.text"); if(f.exists()) { f.createNewFile(); } //写入文件 字节流 FileOutputStream fos = new FileOutputStream(f,true); //ture 代表文件可追加 fos.write("hellow:zhongguo ".getBytes()); fos.close(); //字符流 FileWriter fw = new FileWriter(f,true); fw.write("qwer "); fw.close(); } }
二、读取文本文件
package day05; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; public class Work07 { public static void main(String[] args) throws IOException { //字节流读取文件 FileInputStream fis = new FileInputStream("D:/QQQ/cc.txt"); byte[] buf = new byte[fis.available()]; fis.read(buf); fis.close(); System.out.println(new String(buf)); System.out.println("____________________"); //字符流读取文件 BufferedReader br = new BufferedReader(new FileReader("D:/QQQ/cc.txt")); while (br.ready()) { System.out.println(br.readLine()); } } }
三、复制文本文件
package day05; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; //文件复制 public class Work08 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File f = new File("D:/QQQ","cc.txt"); //使用字节流复制 FileInputStream fis = new FileInputStream(f); FileOutputStream fos = new FileOutputStream(new File("D:/","xxx.txt")); byte[] buf = new byte[1024]; int len = 0; while((len = fis.read(buf)) !=-1) { fos.write(buf, 0, len); } fis.close(); fos.close(); } }