Posts

Showing posts with the label Io

Create A New Line In Java's FileWriter

Answer : If you want to get new line characters used in current OS like \r\n for Windows, you can get them by System.getProperty("line.separator"); since Java7 System.lineSeparator() or as mentioned by Stewart generate them via String.format("%n"); You can also use PrintStream and its println method which will add OS dependent line separator at the end of your string automatically PrintStream fileStream = new PrintStream(new File("file.txt")); fileStream.println("your data"); // ^^^^^^^ will add OS line separator after data (BTW System.out is also instance of PrintStream). Try System.getProperty( "line.separator" ) writer.write(System.getProperty( "line.separator" )); Try wrapping your FileWriter in a BufferedWriter : BufferedWriter bw = new BufferedWriter(writer); bw.newLine(); Javadocs for BufferedWriter here.

Convert Io.StringIO To Io.BytesIO

Answer : It's interesting that though the question might seem reasonable, it's not that easy to figure out a practical reason why I would need to convert a StringIO into a BytesIO . Both are basically buffers and you usually need only one of them to make some additional manipulations either with the bytes or with the text. I may be wrong, but I think your question is actually how to use a BytesIO instance when some code to which you want to pass it expects a text file. In which case, it is a common question and the solution is codecs module. The two usual cases of using it are the following: Compose a File Object to Read In [16]: import codecs, io In [17]: bio = io.BytesIO(b'qwe\nasd\n') In [18]: StreamReader = codecs.getreader('utf-8') # here you pass the encoding In [19]: wrapper_file = StreamReader(bio) In [20]: print(repr(wrapper_file.readline())) 'qwe\n' In [21]: print(repr(wrapper_file.read())) 'asd\n' In [26]: bio.seek(0) Out[26]: 0 ...