文件在 d:/test/a.txt
内容为 Hello
File file=new File("D:\\test\\a.txt");//创建一个路径对象。
byte[] b=new byte[100];//准备好字节数组,100个字节数组读。
int count=0;//用count装载字节数组。
try {FileInputStream fis=new FileInputStream(file);//文件字节输入流。并try catch.
try {while((count=fis.read(b))!=-1){//用while一直读,用count装载read的结果,并判断等于-1,文件读取结束。抛出read的try catch。
String string=new String(b, 0, count);//字节数组转换成字符串。
System.out.println(string);}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
下面是改写内容:
File file2=new File("D:\\test\\c.txt");//创建一个file2对象
String txt="我是中国人";//创建一个字符串
byte[] b2=txt.getBytes();将txt字符串转换为字节数组
FileOutputStream fos=new FileOutputStream(file2);//创建需要写入的文件流对象
fos.write(b2);//写入字节数组
fos.close();关闭流