import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOtest01 {
public static void main(String[] args) throws IOException {
File f = new File("F:/t.txt"); //创建文件对象
if(f.exists()!=true){ //判断文件是否已创建
boolean b = f.createNewFile(); //创建文件
System.out.println(b);
}else{
System.out.println("文件已创建,无需重复");
}
/*写入内容到文件中*/
try{
FileOutputStream os = new FileOutputStream("F:/t.txt"); //创建文件输入流对象
System.out.println("请输入要写入的内容:");
int count,n2 = 520;
byte b2[] = new byte[n2]; //定义存放读入信息的字节数组
count = System.in.read(b2); //读取标准输入流
os.write(b2,0,count); //将字节数组中下标0到count的字节写入流中
System.out.println("输入完毕!");
os.close(); //关闭输出流
}catch(IOException e){
e.printStackTrace();
}
/*读取文件内容,并显示*/
try{
FileInputStream in = new FileInputStream("F:/t.txt"); //创建文件输入流对象
int n = 520; //设定读取字节数
byte b1[] = new byte[n];
in.read(b1,0,n); //读取n个字节放置到b1字节数组中,返回值为实际读取字节的数量
System.out.println(new String(b1));
// //读取n个字节放置到b1字节数组中,返回值为实际读取字节的数量
// while((in.read(b1,0,n)!=-1)&&(n>0)){
// System.out.println(new String(b1));
// }
in.close(); //关闭输入流
}catch(IOException e){
e.printStackTrace();
}
}
}
read() 方法,它从输入流读取一个字符并把该字符作为整数值返回。 当流结束的时候返回 -1。该方法抛出 IOException。