文件的简单读取,FileInputStream类的简单使用

来源:互联网 发布:淘宝加购物车软件 编辑:程序博客网 时间:2024/05/21 18:43
文件输入操作:
FileInputStream类的使用:
1、定义一个数组、整形数、字符串、存放文本的路径;
2、创建一个FileInputStream类对象,read()方法将读取数据放入数组并返回内容的长度;
3、整形数接收read()返回值,获取长度;

4、字符串对象利用构造方法接收数据。

String str=new String(bt,0,bytes);//内容,起始位置下标,长度


bt - 存放在数组中将被转换成字符串的内容;
0 -  数组索引的起始位置;

bytes - 转换的最大长度;


5、使用FileInputStream对象需要进行异常处理;





示例:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

public class FileInputOpration {


public static void main(String[] args) {
String Url = "C:/Users/admin/Desktop/myjava/AreaGirth.java";
byte[] bt = new byte[2048];
int bytes;


try {
FileInputStream fileIn = new FileInputStream(Url);
bytes = fileIn.read(bt);
String str = new String(bt, 0, bytes);//后文有文档说明该方法
System.out.println(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}



附加String构造方法文档提示:
String
public String(byte[] bytes,
      int offset,
      int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's default charset. The length of the 


new String is a function of the charset, and hence may not be equal to the length of the subarray. 
The behavior of this constructor when the given bytes are not valid in the default charset is unspecified. The 


CharsetDecoder class should be used when more control over the decoding process is required.


Parameters:
bytes - The bytes to be decoded into characters
offset - The index of the first byte to decode
length - The number of bytes to decode 
Throws: 
IndexOutOfBoundsException - If the offset and the length arguments index characters outside the bounds of the bytes array



}
0 0
原创粉丝点击