问题描述
public static String read(String file) { StringBuilder sb = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK")); String s; while ((s = in.readLine()) != null) { sb.append(s+"n"); } sb.deleteCharAt(sb.length()-1); in.close(); } catch (IOException ex) { Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex); } return sb.toString(); }将上边代码读取到的内容再用BufferedWriter写到文件中时 换行符都没了如何才能保持String里的格式写入文件啊注:不是做copy用 问题补充:shansun123 写道
解决方案
1、在windows中就用rn,在linux中用n.2、建议LZ不要使用硬编码,而用String LINE_SEPARATOR=System.getProperty("line.separator"),这个LINE_SEPARATOR就是一个回车换行符,这样跨系统也不用怕了.
解决方案二:
public static String read(String file) { StringBuilder sb = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK")); String s; while ((s = in.readLine()) != null) { sb.append(s+"rn"); } sb.deleteCharAt(sb.length()-1); in.close(); } catch (IOException ex) { Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex); } return sb.toString();}
解决方案三:
public static void read(String file) {// StringBuilder sb = new StringBuilder();PrintWriter out = null;BufferedReader in = null; try { out = new PrintWriter(new OutputStreamWriter(new FileOutputStream("aa"))); in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK")); String s; while ((s = in.readLine()) != null) { out.println(s);// sb.append(s+"n"); }// sb.deleteCharAt(sb.length()-1); in.close(); } catch (IOException ex) {// Logger.getLogger(Encrypt.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (in != null) in.close(); } catch (IOException e) {e.printStackTrace();} if (out != null) out.close(); }// return sb.toString();} 改成差不多这个样子,不就可以了?
解决方案四:
引用while ((s = in.readLine()) != null) { 你这不就是读了一行吗???直接把读到的这一行(s)写到文件里不就行了,不要全部拼好啊
解决方案五:
没读懂LZ的意思,能举个例子描述下吗
解决方案六:
用BufferedWriter的println,读一行就写一行
解决方案七:
sb.deleteCharAt(sb.length()-1); 这一行去掉吧。