Which is the fast way to write text file in java?
At the moment i use this way to write a text file:
FileOutputStream fos = new FileOutputStream('FileName');
DataOutputStream dos = new DataOutputStream(fos);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(dos, Charset.forName(this.config.getCharset())));
My file size will be up 3 GB.
Flush the buffer after significant chunk of data is written. FileOutputStream should be just enough for text files. There is no need for using DataOutputStream.
how about
FileOutputStream fos = new FileOutputStream('FileName');
BufferedOutputStream bof = new BufferedOutputStream(fos);
bof.write("some text".getBytes()); // or just byte array
or
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Some text");
You do not need to use DataOutputStream here.
Related
I want to convert PrintWriter object into ByteArrayOutputStream. and this I am displaying as a PDF.
I don't know how you are using PrintWriter exactly (please post your code), but instead of converting objects you can write lines directly to ByteArrayOutputStream like this:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream);
pw.write("example");
pw.flush();
or (flush after closing PrintWriter):
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream);
pw.write("example");
pw.close();
or (auto-flushable):
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream, true);
pw.println("example");
Let me know whether you prefer other solution and add some more details then(your code).
recently i had troubles working with InputStreams and OutputStreams when i was trying to implement a basic file downloader in my android application.. to elaborate things this is how i did it..
i get an InputStream object using the apache HttpClient classes then tried writing the stream to a file.. but strangely when i buffer the InputStream or the OutputStream i get an unreadable file.... this is the code..
//to make the code concise i removed exceptions and stream closing..
private void download(InputStream in,String fileName){
//if i dont use the buffered thing and read directly from in everything is ok
// same is the buffered out i had to use in/outstream
BufferedInputStream bufferedIn = new BufferedInputStream(in);
FileOutputStream fout = new FileOutputStream(new File(fileName));
BufferedOutputstream bufferedOut = new BufferedOutputstream(fout);
int read = -1;
while((read = bufferedIn.read()) != -1){
bufferedOut.write(read);
}
//close the buffers
}
You have to flush the buffered outputstream when you're done with it.
In any case you probably want to flush() your output (done implicitly by close()), but with BufferedOutputStream this is even more important than with a other OutputStreams. If you have a FileOutputStream, the only buffering performed is that of the OS. If you have a BufferedOutputStream, Java performs its own buffering on top of it.
If you use Java 7 or newer, I'd recommend to write the code like this:
try (BufferedInputStream bIn = new BufferedInputStream(in);
BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(fileName))) {
for (int read; ((read = bIn.read()) != -1; )
bOut.write(read);
}
In your case I suspect you were closing the FileOutputStream but not the BufferedOutputStream. Therefore the file was truncated or even empty because the data buffered in the BufferedOutputStream was not flushed.
what about one BufferedOutputStream wrap another BufferedOutputStream? this question is simple. but confused.
As the following code,
OutputStream file = new FileOutputStream("test.txt");
OutputStream buffer = new BufferedOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(buffer); //wrap buffer twice
OutputStream outputStream = new ObjectOutputStream(bufferedOutputStream); // wrap as ObjectOutputStream
BufferedOutputStream bufferedOutputStream1 = new BufferedOutputStream(outputStream); //wrap back as BufferedOutputStream
ObjectOutput output = new ObjectOutputStream(bufferedOutputStream1);
What about it? Question?
If you're asking whether an inefficiency is introduced, the answer is 'no'. The code is optimised to handle that case, or rather the case where the transfer size >= the buffer size.
I open a text file using windows-1251 encoding
FileInputStream is = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"windows-1251"));
and later write the changes like:
RandomAccessFile file = new RandomAccessFile(new File(path), "rw");
try {
file.write(etMainView.getText().toString().getBytes());
file.close();
Toast.makeText(this, "Changes saved", Toast.LENGTH_SHORT)
.show();
//..... Exception handling
The problem is that it messes up all the non-latin letters in the file and when I open it again, all such letters are replaced with some unreadable characters. I guess the RandomAccessFile uses UTF-8 by default which is causing troubles. How can I save the file keeping the encoding I used to open it?
Use .getBytes("windows-1251") instead of .getBytes(); .getBytes() uses the default JVM encoding.
If you want to use the stream apis you can do it this way
RandomAccessFile file = ....;
FileChannel fc = file.getChannel();
OutputStream os = Channels.newOutputStream(fc);
OutputStreamWriter osw = new OutputStreamWriter(os, "windows-1251");
osw.write("Some sring");
osw.flush();
file.close();
What's the difference between using a BufferedReader and a BufferedInputStream?
A BufferedReader is used for reading character data. A BufferedOutputStream is used for writing binary data.
Any classes inheriting from Reader or Writer deal with 16-bit unicode character data, whereas classes inherting from InputStream or OutputStream are concerned with processing binary data. The classes InputStreamReader and OutputStreamWriter can be used to bridge between the two classes of data.
Bufferedreader reads data from a file as a string. BufferedOutputStream writes to a file in bytes. BufferedInputStream reads data in bytes
Sample to Bufferedreader:
try {
BufferedReader br = new BufferedReader(new FileReader(new File(your_file));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
}
Sample to BufferedOutputStream:
//Construct the BufferedOutputStream object
bufferedOutput = new BufferedOutputStream(new FileOutputStream(filename));
//Start writing to the output stream
bufferedOutput.write("Line 1".getBytes());
bufferedOutput.write("\r\n".getBytes());
bufferedOutput.write("Line 2".getBytes());
bufferedOutput.write("\r\n".getBytes());
Bufferedinputstream reads in byte:
Sample
:
//Construct the BufferedInputStream object
bufferedInput = new BufferedInputStream(new FileInputStream(filename));
int bytesRead = 0;
while ((bytesRead = bufferedInput.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
System.out.print(chunk);
}
As the names imply, one is for reading data, and the other is for outputting data.