一、字节输入、输出流
1.InputStream读取文件
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.InputStream; 4 public class Demo { 5 public static void main(String[] args) throws Exception { 6 File file = new File("D://测试文件.txt"); 7 InputStream in = new FileInputStream(file); 8 int fileLength = (int) file.length(); 9 byte b[] = new byte[fileLength]; 10 in.read(b); 11 in.close(); 12 System.out.println("读取的内容是:" + new String(b)); 13 } 14 }
2.OutputStream写入文件
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.io.OutputStream; 4 public class Demo { 5 public static void main(String[] args) throws Exception { 6 File file = new File("D://测试文件.txt"); 7 OutputStream out=new FileOutputStream(file); 8 String str="Java你好!"; 9 byte b[]=str.getBytes(); 10 out.write(b); 11 out.close(); 12 } 13 }
二、字符输入、输出流
1.Reader读取文件
一起读取:
1 import java.io.File; 2 import java.io.FileReader; 3 import java.io.Reader; 4 public class Demo { 5 public static void main(String[] args) throws Exception { 6 File file = new File("D://测试文件.txt"); 7 Reader reader=new FileReader(file); 8 char c[]=new char[1024]; //字符数组 9 int len=reader.read(c); 10 reader.close(); 11 System.out.println("读取的内容是:"+new String(c,0,len)); 12 } 13 }
逐个读取:
1 import java.io.File; 2 import java.io.FileReader; 3 import java.io.Reader; 4 public class Demo { 5 public static void main(String[] args) throws Exception { 6 File file = new File("D://测试文件.txt"); 7 Reader reader=new FileReader(file); 8 char c[]=new char[1024]; //字符数组 9 int temp=0; 10 int len=0; 11 while((temp=reader.read())!=-1) { 12 c[len++]=(char)temp; 13 } 14 reader.close(); 15 System.out.println("读取的内容是:"+new String(c,0,len)); 16 } 17 }
2.Writer写入文件
以覆盖的形式:
1 import java.io.File; 2 import java.io.FileWriter; 3 import java.io.Writer; 4 public class Demo { 5 public static void main(String[] args) throws Exception { 6 File file = new File("D://测试文件.txt"); 7 Writer out=new FileWriter(file); 8 String str="我爱Java"; 9 out.write(str); //将字符串写入输出流 10 out.close(); 11 } 12 }
以追加的形式:
1 import java.io.File; 2 import java.io.FileWriter; 3 import java.io.Writer; 4 public class Demo { 5 public static void main(String[] args) throws Exception { 6 File file = new File("D://测试文件.txt"); 7 Writer out=new FileWriter(file,true); 8 String str=",你也爱Java"; 9 out.write(str); //将字符串写入输出流 10 out.close(); 11 } 12 }