向文件中写入数据
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class IOOperation {
public static void main(String[] args) throws IOException {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
Writer out = new FileWriter(f);
String str = "hello";
out.write(str);
out.close();
}
}
运行结果:在文件中写入hello
其实这个例子和之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。如果想向文件中追加内容,可以将上面的声明out的哪一行换为:
Writer out = new FileWriter(f, true);
从文件中读内容
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class IOOperation {
public static void main(String[] args) throws IOException {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
Reader in = new FileReader(f);
char[] charArr = new char[1024];
int len = in.read(charArr);
in.close();
System.out.println("读取长度:" + len);
System.out.println(new String(charArr, 0, len));
}
}
运行结果:
-----------------------------------------------------------------------
读取长度:5
hello
-----------------------------------------------------------------------
采用循环读取
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class IOOperation {
public static void main(String[] args) throws IOException {
String fileName = "D:" + File.separator + "hello.txt";
File f = new File(fileName);
Reader in = new FileReader(f);
char[] charArr = new char[1024];
int count = 0;
int temp = 0;
while((temp = in.read()) != -1) {
charArr[count++] = (char)temp;
}
in.close();
System.out.println(new String(charArr));
}
}
运行结果:hello
使用字节流好还是字符流好呢?
答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。