分享

基于字符进行读写文件

 玉诗 2016-05-29
基于字符进行操作适用于操作双字节符号的首选。适用于读取文字类文件,并不适用于所有的文件类型,例如图片。



import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class BufferedByStream {

public static void main(String[] args) {
String file = "src/docs/1.txt";
String con = "\r\nhelloJAVA";
writeStream(con,file);
String content = readerStream(file);
System.out.println(content);
}

private static void writeStream(String content,String fileName){
Writer write = null;
BufferedWriter buffer = null;
try {
write = new FileWriter(fileName,true);
buffer = new BufferedWriter(write);
buffer.write(content);
 
 
 
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(buffer != null){
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(write != null){
try {
write.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

private static String readerStream(String fileName) {
String content = null;
Reader reader = null;
BufferedReader buffer = null;
try {
reader = new FileReader(fileName);
buffer = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
String line = new String();
while ((line = buffer.readLine()) != null) {
builder.append(line);
builder.append("\r\n");
}
content = builder.toString();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

return content;
}
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多