0

I am trying to write every line that i get to a test.txt file. However every result needs to be in its own line. Am i missing something or did i not corectly implemented "\n"? For better understanding my code reads 3th work in a line and if that word matches P***ei "*" meaning any letter from a-z (A-Z) or S**ei and returns first word in that line as an result. 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(); } } } 
3
  • Is there a specific reason why you didn't try using println()? Commented Oct 22, 2014 at 9:19
  • if you on windows replace '\n' with '\r\n'. Or just use good text editor (not notepad :) ) Commented Oct 22, 2014 at 9:19
  • 1
    @shyam Because FileWriter does not declare println()... Commented Oct 22, 2014 at 9:25

2 Answers 2

2

Get a System line separator instead of using '\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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Better use a text editor that is not limited to \r\n linebreaks.
0

Add fw.flush() at the end of your program.

Look at the flush method inherited from OutputStreamWriter here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.