注*:这里说的输入输出是针对于java项目来说的,输入指的是从外部文件获取内容输入到java类型中,输出指的是从java类型输出到外部文件。
一、输出:从java对象输出到文件中:
java对象可以是String、StringBuffer、StringBuilder类型等,文件的格式可以是.txt/.doc/.docx格式等。
1. 通过FileWriter类型:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("template/output.txt");
fw.write("java");
fw.close();
}
2. 通过BufferedWriter类型:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("template/output.txt");
BufferedWriter bw = new BufferedWriter(fw);
//使用缓冲区中的方法将数据写入到缓冲区中。
bw.write("hello world !");
bw.newLine();
bw.newLine();
bw.write("!hello world !");
bw.write("!hello world !");
//使用缓冲区中的方法,将数据刷新到目的地文件中去。
bw.flush();
//关闭缓冲区,同时关闭了fw流对象
bw.close();
}
3. 根据BufferedOutputStream( 字节缓冲输入流)类型:
public class Output {
public static void main(String[] args) throws Exception {
//符合Java一种设计模式:装饰者设计模式(过滤器:Filter)
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("template/output.txt")) ;
//写数据
bos.write("hello".getBytes());
//释放资源
bos.close();
}
}
二、输入:读取文件,转换成java对象:
文件的格式可以是.txt/.doc/.docx格式等,可以转换成String、StringBuffer、StringBuilder类型等。
1. 通过BufferedReader类型:
/*
读取word内容并把内容写入到一个String中
@author Draco
*/
import java.io.*;
class FileToString{
public static void main(String[] args) throws IOException{
String s = new String();
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(
new FileReader("c:\\j2sdk\\stream\\3.doc")
);
try {
while((s = in.readLine()) != null) sb.append( s+"\n\r");
in.close();
System.out.println(sb);
}
catch(IOException e){
System.out.println("file error");
}
}
}
2. 根据BufferedInputStream( 字节缓冲输入流)类型:
public class FileToString {
public static void main(String[] args) {
BufferedInputStream bufferedInput = null;
byte[] buffer = new byte[1024];
try {
bufferedInput = new BufferedInputStream(new FileInputStream("template/test.txt"));
int bytesRead = 0;
//从文件中按字节读取内容,到文件尾部时read方法将返回-1
while ((bytesRead = bufferedInput.read(buffer)) != -1) {
//将读取的字节转为字符串对象
String chunk = new String(buffer, 0, bytesRead);
System.out.print(chunk);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {//关闭 BufferedInputStream
if (bufferedInput != null) bufferedInput.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
可以根据自己的项目进行改写,StringBuffer转成String的方法:
StringBuffer sb = "java";
return sb.toString();
(错误代码:)
class FileToString{
public static void main(String[] args) throws IOException{
String s = new String();
StringBuffer sb = new StringBuffer();
BufferedInputStream in = new BufferedInputStream(
new FileInputstream("c:\\j2sdk\\stream\\3.doc")
);
try {
while((s = in.readLine()) != null) sb.append( s+"\n\r");
in.close();
System.out.println(sb);
}
catch(IOException e){
System.out.println("file error");
}
}
}
字节缓冲输出流