write newline into a file

后端 未结 9 1808
慢半拍i
慢半拍i 2020-12-05 05:28

considering the following function

private static void GetText(String nodeValue) throws IOException {

   if(!file3.exists()) {
       file3.createNewFile();         


        
9条回答
  •  星月不相逢
    2020-12-05 06:12

    Change the lines

    if(nodeValue!=null)
        fop.write(nodeValue.getBytes());
    
    fop.flush();
    

    to

    if(nodeValue!=null) {
        fop.write(nodeValue.getBytes());
        fop.write(System.getProperty("line.separator").getBytes());
    }
    
    fop.flush();
    

    Update to address your edit:

    In order to write each word on a different line, you need to split up your input string and then write each word separately.

    private static void GetText(String nodeValue) throws IOException {
    
        if(!file3.exists()) {
            file3.createNewFile();
        }
    
        FileOutputStream fop=new FileOutputStream(file3,true);
        if(nodeValue!=null)
            for(final String s : nodeValue.split(" ")){
                fop.write(s.getBytes());
                fop.write(System.getProperty("line.separator").getBytes());
            }
        }
    
        fop.flush();
        fop.close();
    
    }
    

提交回复
热议问题