import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.*;
//创建文件并完成数据存取操作
public class FileOperator
{
public static void main(String args[]) throws IOException
{
byte[] by=new byte[1000];
String str="I love You forever!";
by=str.getBytes();
File file=new File("c:/test/test.txt");
if(file.exists())
{
System.out.println("文件已存在");
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileOutputStream fos=new FileOutputStream(file);
fos.write(by,0,by.length);//我将这一行代码放到try、catch外面时,少了对该代码的异常处理,出现错误
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis=new FileInputStream(file);
byte[] b=new byte[1000];
while(-1!=(fis.read(b)))
{
System.out.println("读取文件中数据");
}
//将字节数组变为字符串
String str1=new String(b);
System.out.println(str1);
<span style="white-space:pre"> </span>fis.close();
}
}