File_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > File

File

 2012/3/20 13:59:10  djlijian  程序员俱乐部  我要评论(0)
  • 摘要:/***把字符串写到文件中*/publicstaticvoidwrite2File(Stringstr,StringfileName){Filefile=null;OutputStreamWriterosWriter=null;BufferedWriterbufferWriter=null;try{file=newFile(fileName);if(!file.exists()){file.createNewFile();}osWriter=newOutputStreamWriter
  • 标签:file

??? /**
??? ?* 把字符串写到文件中
??? ?*/
??? public static? void write2File(String str,String fileName){
??? ???
??? ??? File file = null;
??? ??? OutputStreamWriter osWriter = null;
??? ??? BufferedWriter bufferWriter = null;
??? ???
??? ??? try {
??? ??? ??? file = new File(fileName);
??? ??? ??? if(!file.exists()){
??? ??? ??? ??? file.createNewFile();
??? ??? ??? }
??? ??? ??? osWriter = new OutputStreamWriter(new FileOutputStream(file,true),"UTF-8");
??? ??? ??? bufferWriter = new BufferedWriter(osWriter);
??? ??? ??? bufferWriter.write(str);
??? ??? ??? bufferWriter.close();
??? ??? } catch (Exception e) {
??? ??? ??? System.err.println("Error: 写入文件出错。。。");
??? ??? ??? e.printStackTrace();
??? ??? }
??? }
??? /**
??? ?* 从文件中读取字符串
??? ?*/
??? public static String readFromFile(String filePath){
??? ???
??? ??? String fileContent = null;
??? ??? File file = null;
??? ??? InputStreamReader streamReader = null;
??? ??? BufferedReader bufferReader = null;
??? ???
??? ??? String line = null;
??? ???
??? ??? file = new File(filePath);
??? ??? if(file.isFile() && file.exists()){
??? ??? ???
??? ??? ??? try {
??? ??? ??? ??? streamReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
??? ??? ??? ??? bufferReader = new BufferedReader(streamReader);
??? ??? ??? ???
??? ??? ??? ??? while((line = bufferReader.readLine()) != null){
??? ??? ??? ??? ??? fileContent += line;
??? ??? ??? ??? }
??? ??? ??? ??? streamReader.close();
??? ??? ??? } catch (Exception e) {
??? ??? ??? ??? System.err.println("Error:从文件中读取字符串时候出错");
??? ??? ??? ??? e.printStackTrace();
??? ??? ??? }
??? ??? }
??? ??? return fileContent;
??? }

发表评论
用户名: 匿名