package byte_base;
import java.io.FileInputStream;
import java.io.IOException;
public class FileViewer {
public static void main(String[] args) {
int a;
try{
FileInputStream fis = new FileInputStream("FileViewerln.txt");
while((a = fis.read())!=-1){
System.out.write(a);
}
}catch(IOException ioe){
System.err.println(ioe);
ioe.printStackTrace();
}
}
}
It is Program, printing text from file.
When I used FileInputStream Class and System.out.write() method, It run very well.
But I tried another way.
I used BufferedOutputStream instead of System.out.write() method.
The bottom is code using BufferedOutputStream class.
package byte_base;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class CopyOfFileViewer {
public static void main(String[] args) {
int a;
try{
FileInputStream fis = new FileInputStream("FileViewerln.txt");
BufferedOutputStream bos = new BufferedOutputStream(System.out);
while((a = fis.read())!=-1){
bos.write(a);
}
}catch(IOException ioe){
System.err.println(ioe);
ioe.printStackTrace();
}
}
}
But this code's result is vacuum.
I think that first code and second code is very similar.
Why did NOT it(Second Code) working well?
You forgot to close OutputStream bos.
bos.close();
Actually It's much better to do your operations in try-with-resources
try (FileInputStream fis = new FileInputStream("FileViewerln.txt");
BufferedOutputStream bos = new BufferedOutputStream(System.out);
) {
while((a = fis.read())!=-1){
bos.write(a);
}
} catch(IOException ioe){
System.err.println(ioe);
ioe.printStackTrace();
}
class InputStream implements Closeable. So its subclasses could be used in try-with-resources.
Ah the age old flush and the Buffered Stream question.
Use the flush method.
Place it after the while loop
bos.flush();
From the docs
The class implements a buffered output stream. By setting up such an
output stream, an application can write bytes to the underlying output
stream without necessarily causing a call to the underlying system for
each byte written.
The key point here is
without necessarily causing a call to the underlying system for each
byte written.
That basically means the data is buffered in memory and not written to the output stream on each write method call.
You should flush the buffer at a suitable interval and close the stream using the close method to force the final buffer out.
Related
I need to copy a .jar file (which is a resource in my project) from a separate runnable jar to the startup folder in windows. Here's the code I have so far.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Installer {
public static void main(String[] args) throws IOException
{
InputStream source = Installer.class.getResourceAsStream("prank.jar");
byte[] buffer = new byte[source.available()];
source.read(buffer);
File targetFile = new File(System.getProperty("user.home") + File.separator + "AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\prank.jar");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
outStream.close();
}
}
My problem is that after the jar file is copied, it is corrupt (although the size of the original and the copy are the same.) Any thoughts on how to do this and have a runnable jar at the end of the process?
Refer to InputStream#available does not work.
The following line
byte[] buffer = new byte[source.available()];
is not correct, as available only return estimate of the size, the jar will be corrupted when estimate is different with actual. (Example from Java – Write an InputStream to a File) seems incorrect as I can't find any reference that guarantee correctness of available for FileInputStream.
Solution from How to convert InputStream to File in Java is more robust,
private static void copyInputStreamToFile(InputStream inputStream, File file)
throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file)) {
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
// commons-io
//IOUtils.copy(inputStream, outputStream);
}
}
You can consider to use
IOUtils#copy(InputStream, OutputStream)
Files#copy(InputStream, Path, CopyOption...) suggested by Holger for jdk 1.7 or above
Try this -
Path source = Paths.get("location1/abc.jar");
Path destination = Paths.get("location2/abc.jar");
try {
Files.copy(source, destination);
} catch(FileAlreadyExistsException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I Have 3 objects of Person type and i write them to my file Person.person and than i read them one by one but when i run my program again i get the same 3 objets written as when i run it for the firts time.How to add those 3 objects to my file again and again every time i run my program.I want from it to be the same 3 objects or some other objects but they need to be added to the end of my file.
And how to get that data when i want to read that file?
package pisanjeUFajl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
public class Serilizacija {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Person person = new Person("Jovan", "Dukic");
Person person2 = new Person("Stanko", "Maca");
Person person3 = new Person("Tole", "Lopove");
File file = new File("C:\\Users\\Jovan\\Desktop\\Person.person");
if (!(file.exists())) {
file.createNewFile();
}
ObjectOutputStream outputStream = null;
outputStream = new ObjectOutputStream(new BufferedOutputStream(new
FileOutputStream(file)));
outputStream.writeObject(person);
outputStream.reset();
outputStream.writeObject(person2);
outputStream.reset();
outputStream.writeObject(person3);
outputStream.reset();
outputStream.close();
ObjectInputStream inputStream = null;
inputStream = new ObjectInputStream(new BufferedInputStream(new
FileInputStream(file)));
int count = 0;
Person object = null;
I added more objects to my file but when i wanted to read them i got and error:
Exception in thread "main" java.io.StreamCorruptedException:
invalid typecode:AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at pisanjeUFajl.Serilizacija.main(Serilizacija.java:46)
It read just the first 3 objects which were added the first to my file.
try {
while (true) {
object = (Person) inputStream.readObject();
count++;
System.out.println(object);
}
} catch (EOFException error) {
System.out.println("\nEnd of file reacher - objects read = " +
count);
}
inputStream.close();
}
}
Use for writing object
ObjectOutputStream outputStream = new ObjectOutputStream(new
FileOutputStream(new File("test")));
Use it for appending object at end of file
ObjectOutputStream outputStream2 = new ObjectOutputStream(new FileOutputStream("test", true)) {
protected void writeStreamHeader() throws IOException {
reset();
}
};
for reading
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("test"));
Use the Constructor of FileOutputStream that accepts a boolean as a parameter.
If its set to true, everything written to file through this Stream is appended to the existing content. Constructor looks like this:
FileOutputStream(File file, boolean append)
I try to output the content of a text file. But I don't know how to work with the RandomAccessFile. I haven't found good examples at google. I hope for some help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
File src = new File ("C:/Users/hansbaum/Documents/Ascii.txt");
cat(src);
}
public static void cat(File quelle){
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
// while(datei.length() != -1){
// datei.seek(0); //
// }
} catch (FileNotFoundException fnfe) {
System.out.println("Datei nicht gefunden!");
} catch (IOException ioe) {
System.err.println(ioe);
}
}
}
related from doc
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
String line;
while ( (line = datei.readLine()) != null ) {
System.out.println(line);
}
System.out.println();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
System.err.println(ioe);
}
What makes you think you need a RandomAccessFile? The easiest way is probably to use nio's convenience methods. With those, reading a file is as close to a one-liner as it gets in Java.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.IOException;
class Test {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("./Test.java"), StandardCharsets.UTF_8);
for (String l: lines)
System.out.println(l);
}
}
Be aware however that this is not a good idea if you happen to work with very large files as they might not fit into memory.
Try to create Stream from FileChannel to read and write in another file out.txt like this:
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r").getChannel();){
// Construct a stream that reads bytes from the given channel.
InputStream is = Channels.newInputStream(rChannel);
File outFile = new File("out.txt");
// Create a writable file channel
WritableByteChannel wChannel = new RandomAccessFile(outFile,"w").getChannel();
// Construct a stream that writes bytes to the given channel.
OutputStream os = Channels.newOutputStream(wChannel);
// close the channels
is.close();
os.close();
Using the following libraries:
qrgen-1.2, zxing-core-1.7, and
zxing-j2se-1.7 I generated QRCode:
ByteArrayOutputStream out = QRCode.from(output.toString()).withSize(1000,1000).to(ImageType.PNG).stream();
FileOutputStream fout = new FileOutputStream(new File("D:\\QR_Code.JPG"));
fout.write(out.toByteArray());
fout.flush();
fout.close();
What I intend to do with it, is to send code to a method that accepts java.awt.Image.
How can I convert an instance of QRCode class into an instance of Image class without creating QRCode.JPG at the first place? As I see, this library doesn't provide users with methods that can carry this out, so is it possible at all? May be I can convert stream to Image?
Simply write the qr code to a byte array output stream then use byte array in the stream to create a BufferedImage.
import net.glxn.qrgen.QRCode;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
public static BufferedImage generate() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
QRCode.from("http://www.stackoverflow.com").writeTo(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return ImageIO.read(bais);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I have a simple txt file that will save only 1 word, but whenever I restart the program everything inside the data.txt is deleted - I don't know why?
The whole class code:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class InfoSaver {
File data = new File("data.txt");
FileOutputStream fos;
PrintStream writer;
FileInputStream fis;
DataInputStream reader;
public void init() throws IOException{
fos = new FileOutputStream(data);
writer = new PrintStream(fos);
fis = new FileInputStream(data);
reader = new DataInputStream(fis);
}
public void writeData(String info) {
writer.println(info);
}
public String readData() throws IOException{
return reader.readLine();
}
public void close() throws IOException{
writer.close();
reader.close();
}
}
To add to an existing file instead of overwriting it, use FileOutputStream's constructor that lets you open it in append mode.
fos = new FileOutputStream(data, true);
Because of this line:
fos = new FileOutputStream(data);
This version of the constructor of FileOutputStream will overwite the file, but you could use this version:
public FileOutputStream(File file,
boolean append)
throws FileNotFoundException
You'd have to specify that you want to append to the file by setting the append field to true.
You're not appending new information to the file, you're overwriting it.
Anytime you just open it in the
fos = new FileOutputStream(data);
command, it gets emptied, no matter if you have saved anything inside it or not.
Your FileOutputStream is overwriting your file. If you want to append to the end of the file you need to specify that:
fos = new FileOutputStream(data, true);
When you encounter unexpected behavior it's a good idea to check the API to ensure the functions you're calling are doing what you expect. Here is the API for the FileOutputStream constructor.