对文件内容按字符读取
public class WriteRead1 {
public static void main(String[] args) throws IOException {
write1();
read1();
}
private static void read1() throws IOException {
File file = new File("c:/temp/a.txt");
FileReader fr = new FileReader(file);
char[] ch = new char[100];
fr.read(ch);
for (char c:ch){
System.out.println(c);
}
}
private static void write1() throws IOException {
File file = new File("c:/temp/a.txt");
//如果文件不存在则进行新建文件
if (!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
fw.write("Hello world");
fw.flush();
fw.close();
}
}
BuffredReader和BufferedWriter
对文件内容进行整行读取
public class WriteRead2 {
public static void main(String[] args) throws IOException {
write2();
read2();
}
private static void read2() throws IOException {
File file = new File("c:/temp/a.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
private static void write2() throws IOException {
File file = new File("c:/temp/a.txt");
//如果文件不存在则新建文件
if (!file.exists()){
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write("Hello world");
bw.newline();
bw.flush();
bw.close();
}
}
FileInputStream和FileOutputStream
以字节的形式写入文件,读取文件时先读取字节数组,再将字节数组转换为字符串形式
public class WriteRead3 {
public static void main(String[] args) throws IOException {
write3();
read3();
}
private static void read3() throws IOException {
File file = new File("c:/temp/a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] bys = new byte[100];
while (fis.read(bys, 0, bys.length) != -1) {
System.out.println(new String(bys));
}
fis.close();
}
private static void write3() throws IOException {
File file = new File("c:/temp/a.txt");
//如果文件不存在则新建文件
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
fos.write("Hello world".getBytes());
fos.close();
}
}



