您的位置:首页 > 其它

io类一些简单操作(复习)

2007-06-15 11:18 501 查看
java中提供了io类库,可以轻松的用java实现对文件的各种操作。

最近复习一下io类的一些常用的方法。

import java.io.*;

class FileTest
{
public static void makeNewDir()
{
String filePath="C://测试1//";
//filePath=filePath.toString();//中文转换
File myFilePath=new File(filePath);
if(!myFilePath.exists())
myFilePath.mkdir();
}

public static void makeNewFile() throws Exception
{
String filePath="c://测试1//newFile.txt";
//filePath=filePath.toString();
File f=new File(filePath);
if(!f.exists())
f.createNewFile();
FileWriter fw=new FileWriter(f);
PrintWriter myFile=new PrintWriter(fw);
String content1 ="这是测试数据1";
String content2 ="这是测试数据2";
//String strContent = content.toString();
myFile.println(content1.toString());
myFile.write(content2.toString());
fw.close();
}

public static void deleteFile()
{
String filePath="c://测试1//newFile.txt";
//filePath=filePath.toString();
File myDelFile=new File(filePath);
if(myDelFile.exists())
{
myDelFile.delete();
System.out.println(filePath+"删除成功!!!");
}
else
{
System.out.println(filePath+"该文件不存在");
}
}

public static void copyFile() throws Exception
{
int bytesum=0;
int byteread=0;
//file:读到流中
FileInputStream fis=new FileInputStream("c://测试1//newFile.txt");
FileOutputStream fos=new FileOutputStream( "c://测试//copyFile.txt");
byte[] buffer =new byte[2000];
int length;
while ((byteread=fis.read(buffer))!=-1)
{
System.out.println(byteread);
bytesum+=byteread;
System.out.println(bytesum);
fos.write(buffer,0,byteread);
}
fis.close();
}

public static void main(String[] args)
{
System.out.println("Test File");
makeNewDir();
try
{
makeNewFile();
copyFile();
}
catch (Exception ex)
{
ex.printStackTrace();
}
deleteFile();

}
}

可以复制到EDITPULS自己试一下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: