①读取文档的内容:
public class ReadFile {
public static void main(String[] args){
readFile("C:\\Users\\Administrator\\Desktop\\构造方法.txt");
}
public static void readFile(String fielname){
//创建流
try {
InputStream is = new FileInputStream(fielname);
//创建缓存区域
byte buffer[] = new byte[is.available()];
//读取文件字节
is.read(buffer);
//对字节处理
String str = new String(buffer);
System.out.println(str);
//关闭流
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
②对文档的输入:这里对输入的内容有点不一样(注意汉字的写入方式)
public class WriteFile {
public static void main(String[] args) throws IOException{
WriteFile wf = new WriteFile();
wf.writefile("256", "D:\\text.txt");
}
public void writefile(String content,String fileName) throws IOException{
//创建流
OutputStream os = new FileOutputStream(fileName);
//获取所需要获得的内容
byte[] bytes = content.getBytes();
//写出内容
os.write(bytes);
os.write(123);//写的是123对应的ASCII码,在txt文档中显示的是{
os.write(123456);//其实写的是低八位(一个字节)的数据,>255的数写进去的仅仅是它对应的二进制的低八位
//如果需要实现将一个int类型的数据写进去的话,首先需要做一个封装
DataOutput dinput = new DataOutputStream(os);
int x=123456;
dinput.writeInt(x);
String str1 ="你好";
os.write(str1.getBytes("gbk")); // 写汉字进去,gbk必须加双引号
//刷新
os.flush();
//停止流
os.close();
InputStream is = new FileInputStream(fileName);
is.read(bytes);
is.close();
}
}