您的位置:首页 > 其它

I/O相关知识复习二

2014-06-17 22:20 176 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: