读数据:
public static String txt2String(){ File file = new File("G:/data/swf/data.txt"); StringBuilder result = new StringBuilder(); try{ InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader br = new BufferedReader(isr);//构造一个BufferedReader类来读取文件 String s = null; while((s = br.readLine())!=null){//使用readLine方法,一次读一行 result.append(System.lineSeparator()+s); } br.close(); }catch(Exception e){ e.printStackTrace(); } return result.toString(); }
写入数据:
public static void writeFile(String str) throws IOException { //写入中文字符时解决中文乱码问题 FileOutputStream fos=new FileOutputStream(new File("G:/data/swf/data.txt"),true); OutputStreamWriter osw=new OutputStreamWriter(fos, "UTF-8"); BufferedWriter bw=new BufferedWriter(osw); bw.write(str+","); //注意关闭的先后顺序,先打开的后关闭,后打开的先关闭 bw.close(); osw.close(); fos.close(); }