Reading file from getResourceAsStream excludes new line

I am reading a resource from getResourceAsStream, adding all the text to a StringBuilder and writing the contents to a new file. However, the text is returned without newlines. When I do the same, but read the file without getResourceAsStream, it works fine.

The code is as follows:

InputStream styleFile = this.getClass().getResourceAsStream( "/path/path/path/some.css"); BufferedReader bufRead = new BufferedReader(new InputStreamReader(styleFile)); StringBuilder builder = new StringBuilder(); int nextchar; while ((nextchar = bufRead.read()) != -1) { builder.append((char)nextchar); } FileWriter outFile; try { outFile = new FileWriter(newStyleFile); } catch (IOException e) { //Log } PrintWriter out = new PrintWriter(outFile); out.write(builder.toString()); out.close(); 
+4
source share
1 answer

If you use BufferedReader.readLine (), it reads everything until the new char line. A new line character is not added to the end of the received characters. This is similar to tokenization on a new line character .. as for BufferedReader.read (), I'm not too sure why a new line is skipped. The jdk source has something like this:

 public int read() throws IOException { synchronized (lock) { ensureOpen(); for (;;) { if (nextChar >= nChars) { fill(); if (nextChar >= nChars) return -1; } if (skipLF) { skipLF = false; if (cb[nextChar] == '\n') { nextChar++; continue; } } return cb[nextChar++]; } } } 

Anyway for your case .. Its easy to write a program that displays a new line ...

 BufferedReader br=new BufferedReader(new InputStreamReader(styleFile)); StringBuilder builder = new StringBuilder(); String line=null; while((line=br.readline())!=null){ builder.append(line).append("\n"); } // then write to the new file... 
+2
source

All Articles