简体   繁体   English

如何在Java中写入新的文本文件

[英]how to write to new text file in java

I am trying to write every line that i get to a test.txt file. 我正在尝试将每行写入test.txt文件。 However every result needs to be in its own line. 但是,每个结果都必须放在自己的行中。 Am i missing something or did i not corectly implemented "\\n"? 我是否缺少某些内容或没有明确实现“ \\ n”? For better understanding my code reads 3th work in a line and if that word matches P***ei "*" meaning any letter from az (AZ) or S**ei and returns first word in that line as an result. 为了更好地理解,我的代码读取了一行的第三篇文章,并且如果该单词与P *** ei“ *”相匹配,则表示a(AZ)或S ** ei中的任何字母,并因此返回该行中的第一个单词。 The code worked but now when i write to file it doesnt print each word in its own line. 该代码有效,但是现在当我写入文件时,它不会在自己的行中打印每个单词。

package test;

 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileReader;
  import java.io.FileWriter;
  import java.io.IOException;
  import java.util.regex.Pattern;

public class moja {



    public static void main(String[] args) {
        try {
            File file = new File("SloveneLexicon.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            StringBuffer stringBuffer = new StringBuffer();
            String vrstica;
            File test = new File("test.txt");
            FileWriter fw = new FileWriter(test);
            while ((vrstica = bufferedReader.readLine()) != null) {

                String s = vrstica;
                String[] dobi_besedo_v_vrstici = s.split("\\s+");
                String prva_beseda = dobi_besedo_v_vrstici[0];
                String tretja_beseda = dobi_besedo_v_vrstici[2];

                Pattern ena = Pattern.compile("S[a-zA-z]{2}ei");
                    if(ena.matcher(tretja_beseda).matches()){
                    fw.write(prva_beseda+'\n');}
                Pattern dva = Pattern.compile("P[a-zA-z]{3}ei");
                    if(dva.matcher(tretja_beseda).matches()){
                        fw.write(prva_beseda+'\n'); 
                    }
                }


            bufferedReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Get a System line separator instead of using '\\n' 获取系统行分隔符,而不是使用'\\ n'

            String newLine = System.getProperty("line.separator");

            Pattern ena = Pattern.compile("S[a-zA-z]{2}ei");
                if(ena.matcher(tretja_beseda).matches()){
                fw.write(prva_beseda + newLine);}
            Pattern dva = Pattern.compile("P[a-zA-z]{3}ei");
                if(dva.matcher(tretja_beseda).matches()){
                    fw.write(prva_beseda + newLine); 
                }

Add fw.flush() at the end of your program. 在程序末尾添加fw.flush()。

Look at the flush method inherited from OutputStreamWriter here . 这里查看从OutputStreamWriter继承的flush方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM