文件的存储
package IO;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* 将str数组中的字符串一行一行的输出到bw.txt中
* @author 人可
*
*/
public class Writer {
public static void main(String[] args) {
BufferedWriter bw = null;
String str[] = {"锄禾日当午","汗滴禾下次","谁知盘中餐","粒粒皆辛苦"};
try {
bw = new BufferedWriter(//缓冲流(字符) BufferedOutputStream是针对字节的缓冲输出流
new OutputStreamWriter(//转换流,用于将要写入到字节流中的字符按指定字符集编码成字节
new FileOutputStream("bw.txt")));//字节文件流流
for(String s:str) {
bw.write(s);//一次写入一行
bw.newLine();//写入分行符
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(null!=bw);
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
文件的读写
package IO;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* 将bw.txt中的内容一行一行的存储到list数组中
* @author 人可
*
*/
public class Reader {
public static void main(String[] args) {
BufferedReader br = null;
List<String> strs = new ArrayList<String>();
try {
br = new BufferedReader(//缓冲流(字符) BufferedInputStream是针对字节的缓冲输出流
new InputStreamReader(//转换流,用于将要字节流中读取到的字节按指定字符集解码成字符
new FileInputStream("bw.txt")));//文件流
String line = null;
while(null!=(line=br.readLine())) {
strs.add(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(String str:strs) {
System.out.println(str);
}
}
}
文件的复制
package shiyan6.IO;
/**
*
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TextCopyText {
public static void main(String[] args) {
BufferedReader bfr = null;
BufferedWriter bfw = null;
int c = 0;
try {
bfr = new BufferedReader(new FileReader(".\\Text\\IO.txt"));
bfw = new BufferedWriter(new FileWriter(".\\Text\\dest.txt"));
String str = null;
while ((str = bfr.readLine()) != null) {
bfw.write(str);
bfw.newLine();
}
bfw.flush();
System.out.println("文件复制成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bfr != null) {
bfr.close();
}
if (bfw != null) {
bfr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容