Java IO的一些列子

Write()方法写入文件

public static void main(String[] args){
try{
BufferedWriter out = new BufferedWriter(new FileWriter("D:\\temp\\runoon.txt"));//创建文件
out.write("cainiaojiaocheng");//向文件中写入字符串
out.close();//关闭文件。运行之后查看目录下应该生成文件,并且文件中有写入的字符串
System.out.println("create file successfully");
}catch(IOException e){

}

}

//用readLine()从文件中读取数据
try{
BufferedReader in = new BufferedReader(new FileReader("D:\\temp\\runoon.txt"));//获取文件地址
String str;//创建一个字符串对象来缓存下读出来的字符串
while((str=in.readLine())!=null){
System.out.print(str);
}
}catch(IOException e){
System.out.println(e);
}
创建临时文件,向文件中对家数据
import java.io.*;


/**
* Created by Sandy.Liu on 2017/8/8.
*/
public class CreateTempFile {
public static void main(String[] args){
try {
File fileDir = new File("D://Temp//");
File tempFile = File.createTempFile("createTempFile", ".txt",fileDir);
tempFile.deleteOnExit();
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
bw.write("String 1");
bw.close();
System.out.println("temp file is created");

//向文件中追加数据,这里注意不要创建一个新的BufferedWriter对象,要用之前的对象,不然会再创建一个新的tempfile,而不是之前的那个对象追加
bw = new BufferedWriter(new FileWriter(tempFile,true));
bw.write("string 2");
bw.close();
BufferedReader br = new BufferedReader(new FileReader(tempFile));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
br.close();
}catch (IOException e){
System.out.println(e);
}
}
}
重命名
import java.io.*;

/**
* Created by Sandy.Liu on 2017/8/8.
*/
public class FileRename {
public static void main(String[] args){
File oldName = new File("D://Temp//TestSource.txt");
File newName = new File("D://Temp//TestSource1.txt");
if(oldName.renameTo(newName)){
System.out.println("rename successfully");
}else{
System.out.println("Error");
}
}
}

复制文件,用到BufferedWriter,BufferedReader,InputStream,OutputStream

import java.io.*;

/**
* Created by Sandy.Liu on 2017/8/8.
*/
public class CopyFile {
public static void main(String[] args){
try {
//创建文件,并向文件中写入数据
BufferedWriter bf = new BufferedWriter(new FileWriter("D://Temp//TestSource.txt"));
bf.write("this is for test copy files from TestSource.txt to TestTarget.txt");
bf.close();

//读出文件到buffer里,为写入另一个文件做准备
InputStream is = new FileInputStream(new File("D://Temp//TestSource.txt"));
byte[] buf = new byte[1024];

//把buffer里的数据写入到目标文件中去
OutputStream ot = new FileOutputStream(new File("D://Temp//TestTarget.txt"));
int len;
while((len=is.read(buf))>0){
ot.write(buf,0,len);
}

//从目标文件中读取字符串,输出到控制台
BufferedReader br = new BufferedReader(new FileReader("D://Temp//TestTarget.txt"));
String str;
while((str=br.readLine())!=null){
System.out.println(str);
}
}catch(IOException e){
System.out.println(e);
}
}
}



posted on 2017-08-08 17:45  永恒自由森林  阅读(230)  评论(0编辑  收藏  举报

导航