您的位置:首页 > 编程语言 > Java开发

Java IO流基本操作

2016-04-01 20:35 501 查看

Java IO流基本操作

1.创建一个文件,并写入数据。

public class Test {
public static void main(String[] args) throws Exception {
File file = new File("G:/test.txt");
//如果文件不存在则创建一个
if(!file.exists()) {
file.createNewFile();
}
//使用字节流
FileOutputStream fos = new FileOutputStream(file);
fos.write("Java".getBytes());
//使用字符流(需要刷新缓冲区)
FileWriter fw = new FileWriter(file);
fw.write("Java");
fw.flush();
//最后不要忘了关闭流
fos.close();
fw.close();
//使用缓冲流包装(需要刷新缓冲区)
}
}


FileOutputStream默认情况下是覆盖之前的文件内容,如果要在之前的内容上追加,

使用FileOutputStream fos = new FileOutputStream(file, true)或者FileWriter fw = new FileWriter(file, true);

2.拷贝文件。

File oldFile = new File("G:/old.txt");
File newFile = new File("G:/new.txt");
/*采用字节流方式*/
FileInputStream fis = new FileInputStream(oldFile);
FileOutputStream fos = new FileOutputStream(newFile);
// 缓冲区
byte[] buffer = new byte[1024];
// 每次读取的长度
int len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();

/*采用字符流方式*/
FileReader fr = new FileReader(oldFile);
FileWriter fw = new FileWriter(newFile);
char[] buffer = new char[2];
int len = 0;
while((len = fr.read(buffer)) != -1) {
fw.write(buffer, 0, len);
}
fw.flush();
fw.close();
fr.close();


3.创建目录。

File file = new File("G:/dir1/dir2");
//如果不存在该目录就创建
if(!file.exists()) {
file.mkdirs();
}


如果父目录存在的话,就用mkdir()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: