zoukankan      html  css  js  c++  java
  • Java 写文件实现换行

    第一种:

    写入的内容中利用 进行换行

    File file = new File("D:/text");
    		
    			try {
    				if(!file.exists())
    				file.createNewFile();
    				
    				FileOutputStream out=new FileOutputStream(file,false);
    				StringBuffer sb=new StringBuffer();
    				sb.append("10600257100120161201153103010 
    ");
    				sb.append("120161201KBS571009886631浙江目录上传120161201094425210009302359591120110422KBS00005595530ZZA571ZZA20161201094435fanzhipeng2000
    ");
    				out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
    				out.flush();
    		                out.close();
    				/*
                        FileOutputStream out = new FileOutputStream(file);  
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8")); 
                       writer.write(json);
    writer.close();  
                                    */
                       } catch (IOException e) { e.printStackTrace(); }

      第二种:

    利用BufferedWriter的newline()方法

    File file = new File("D:/text");
    		
    			try {
    				if(!file.exists())
    				file.createNewFile();
    				
    				FileWriter  out=new FileWriter (file);
    				BufferedWriter bw= new BufferedWriter(out);  
    				bw.write("10600257100120161201153103010 ");  
    				bw.newLine();  
    				bw.write("120161201KBS571009886631浙江目录上传120161201094425210009302359591120110422KBS00005595530ZZA571ZZA20161201094435fanzhipeng2000");  
    				bw.newLine();   	
    				bw.flush();
    				bw.close();
    								
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		
    

      但是newLine在使用中可能会出现问题:

    不同系统的换行符:

        windows -->  

        Linux         -->  

        mac         -->  

        我们一般开发是在 windows 下开发,而服务器一般情况下都是 linux。

        如果我们使用 newline 函数换行,在本机测试的时候,因为是 windows 环境,换行符是 ,打开文件时候自然文件是换行处理,没有问题。

       当我们部署到服务器时候,服务器是 linux 环境,newline 读取系统换行符是 ,导出到文件,文件的换行符是 ,当我们把这个文件通过浏览器下载到 windows 时候,再打开文件将会出现没有换行的问题。因为 windows 下对于  的解释并不是换行符。

       所以,我们在开发时候,如果需要指定文件在某些地方换行,则不能使用 newline 方法。必须手动指定换行符:  因为按照上面列举的不同系统换行符看,如果字符串的末尾是   在三个系统中,查看该文件,都会解释为换行。

    简单整理!!

  • 相关阅读:
    TCP/IP笔记 一.综述
    Makefile的规则
    u盘安装ubuntu10.04 server.txt
    浅谈数据库技术,磁盘冗余阵列,IP分配,ECC内存,ADO,DAO,JDBC
    cocos2d-js 热更新具体解释(一)
    C#一个托付的样例
    JAVA学习之 异常处理机制
    阿里巴巴校招内推简历筛选方案
    《凑硬币》 动态规划算法入门
    android 读取xml
  • 原文地址:https://www.cnblogs.com/renjie0520/p/6132277.html
Copyright © 2011-2022 走看看