标签:
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 public class FileIO { 7 public static void main(String[] args) throws IOException { 8 String FileName="D:"+File.separator+"io.txt"; 9 File file=new File(FileName); 10 InputStream inputStream=new FileInputStream(file); 11 byte[] by=new byte[1024]; 12 inputStream.read(by); 13 inputStream.close(); 14 System.out.println(new String(by)); 15 } 16 }
注意:该示例中由于b字节数组长度为1024,如果文件较小,则会有大量填充空格。我们可以利用in.read(b);的返回值来设计程序,如下案例:
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 public class FileIO { 7 public static void main(String[] args) throws IOException { 8 String FileName="D:"+File.separator+"io.txt"; 9 File file=new File(FileName); 10 InputStream inputStream=new FileInputStream(file); 11 byte[] by=new byte[1024]; 12 int len= inputStream.read(by); 13 inputStream.close(); 14 System.out.println("读入长度:"+len); 15 System.out.println(new String(by)); 16 } 17 }
注意:观察上面的例子可以看出,我们预先申请了一个指定大小的空间,但是有时候这个空间可能太小,有时候可能太大,我们需要准确的大小,这样节省空间,那么我们可以这样做:
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 6 public class FileIO { 7 public static void main(String[] args) throws IOException { 8 String FileName="D:"+File.separator+"io.txt"; 9 File file=new File(FileName); 10 InputStream inputStream=new FileInputStream(file); 11 byte[] by=new byte[(int)file.length()]; 12 int len= inputStream.read(by); 13 inputStream.close(); 14 System.out.println("读入长度:"+len); 15 System.out.println(new String(by)); 16 } 17 }
注意:上面的几个例子都是在知道文件的内容多大,然后才展开的,有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。
1 public class FileIO { 2 public static void main(String[] args) throws IOException { 3 String FileName="D:"+File.separator+"io.txt"; 4 File file=new File(FileName); 5 InputStream inputStream=new FileInputStream(file); 6 byte[] by=new byte[1024]; 7 int count=0; 8 int temp=0; 9 while((temp=inputStream.read())!=-1){ 10 by[count++]=(byte) temp; 11 12 } 13 inputStream.close(); 14 System.out.println("读入长度:"+file.length()); 15 System.out.println(new String(by)); 16 } 17 }
注意:当读到文件末尾的时候会返回-1.正常情况下是不会返回-1的。
1 public class FileIO { 2 public static void main(String[] args) throws IOException { 3 String FileName="D:"+File.separator+"io.txt"; 4 File file=new File(FileName); 5 OutputStream out=new FileOutputStream(file); 6 String str="hello,io"; 7 byte[] by=str.getBytes(); 8 out.write(by); 9 out.close(); 10 } 11 }
注意:会覆盖以前的内容
1 public class FileIO { 2 public static void main(String[] args) throws IOException { 3 String FileName="D:"+File.separator+"io.txt"; 4 File file=new File(FileName); 5 OutputStream out=new FileOutputStream(file,true); //true表示追加模式,否则为覆盖 6 String str="\r\nhello,io";//换行 7 byte[] by=str.getBytes(); 8 out.write(by); 9 out.close(); 10 } 11 }
标签:
原文地址:http://www.cnblogs.com/gugibv/p/5144436.html