reading file using BufferedInputStream - java

I am new to Java programming and I was reading the a file using the BufferedInputStream(). Can someone tell me why I can't read my file? If I print obj.read(), it returns -1 everytime. Instead it should return the unicode value of every character that the stream is reading.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("myfile.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
while(obj2.read()!=-1)
{
System.out.print((char) obj2.read());
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
}
But after introducing a local variable the code works, why???
package com.company;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("riten.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
int a;
while((a=obj2.read())!=-1)
{
System.out.print((char)a);
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
}

You need to read from your BufferedInputStream and not from the FileInputStream. You are mixing things here.
But in addition to your code you need to properly handle streams, i.e. when you open a file you need to close those afterwards.
A fix of your code. I added a local variable to store the read character and then cast it to a character.
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("myfile.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
int c;
while((c = obj2.read())!=-1)
{
System.out.print((char) c);
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}

Related

I can't write on multiple lines in a txt file in java

So I'm trying to write in a text file, nothing too complicated, but for some reason the new text that i want to add doesn't change lines, it keeps going on the same line, and I can't figure out why. The irrelevant parts are being commented so don't worry about them.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
public static void main( String args[]) {
int a = 32;
int b=12;
int c=33;
List<Integer> myList = new ArrayList();
myList.add(a);
myList.add(b);
myList.add(c);
/* for(int s:myList)
{
System.out.println(s);
}
*/
//Om ar= new Om("Alex",21,185);
//System.out.println(ar);
try{
File myObj = new File("filename.txt");
if(myObj.createNewFile()){
System.out.println("File created " + myObj.getName());
}
else
{
System.out.println("File already exists");
}
}
catch (IOException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
try {
FileWriter myWriter = new FileWriter("filename.txt");
for(int i=1;i<10;i++)
{
myWriter.append("This is a new file, nothing sus here."+i + " ");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Wrap your FileWriter in a BufferedWriter to make writing to the file more efficient.
Then you can use the newLine() method of the BufferedWriter to add a newline String to the file as you require. The newLine() method will write out the appropriate string for your current platform.

Java not reading all object from file

So I have a real strange bug, I get my objects into a arraylist, write them out to see if everything is there, everything checks out, i write them down into a file, eveything is there when I open the file, but when i go on to read them some objects are for unknow reasons not read, like that entry isnt exisitng in the file, but I can see in the file that they are there. Anyone know that I'm missing here?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class ReadWriteTD {
public static void write(ArrayList<Tokendata> list) {
try {
FileOutputStream f = new FileOutputStream(new File("src/resources/TokenProfiles"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
list.forEach(a -> {
try {
o.writeObject(a);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
}
}
public static ArrayList<Tokendata> read() {
ArrayList<Tokendata> list = new ArrayList<Tokendata>();
try {
FileInputStream fi = new FileInputStream(new File("src/resources/TokenProfiles"));
ObjectInputStream oi = new ObjectInputStream(fi);
Boolean cond = true;
while(cond){
if(oi.readObject() != null)
list.add((Tokendata) oi.readObject());
else cond=false;
}
oi.close();
fi.close();
}catch(Exception e){
}
//list.forEach(a -> System.out.print(a.toString()));
return list;
}
}
This is the problem:
if(oi.readObject() != null)
list.add((Tokendata) oi.readObject());
That's calling readObject() twice per iteration. The result of the first call is ignored other than to check whether or not it's null. You just want something like:
Object obj;
while ((obj = oi.readObject()) != null) {
list.add((Tokendata) obj);
}
No need for your cond variable, and now you're only calling readObject once per iteration.

FileOutputStream doesn't show FileNotFoundException

for FileOutputStream, it will throw a FileNotFoundException if the file doesn't exist, but it will create it if it can.
I dont have a Sample.txt in my project root
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is:
I cannot see the Output of the "File Not Found" from the Terminal. How did it happen?
Thank you
You can set Sample.txt as a File first and check if it exists with .canWrite()
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}

Console output to file using multithreading

Is there a way to save the whole console output to a file when multithreading? I'm working with 5 threads. I had this idea that i can put a printstream in the run-method.
example:
public void run() {
try{
PrintStream out = new PrintStream(file);
stopExecute stop = new stopExecute();
Thread t = new Thread(stop);
Scanner in = new Scanner(System.in);
t.start();
while (!in.hasNextLine())
{
classThatUsingMultipleThrads();
System.out.println("Finished");
anotherClassThatUsingThreads();
System.out.println("Finished");
}
System.out.prinln("User stopped the execution");
stop.keepRunning = false;
System.setOut(out);
}
catch(IOException e){System.out.println(e);}
Problem here is that it's only saving the output "User stoped the execution" and everything in the whileloop are not saved. Or the outputstream from other classes.
I've tried to put the
System.setOut(out);
in the while-loop, but didn't help.
Edit: Spell correction
try {
System.setOut(new PrintStream(new File("output-file.txt")));
}
catch (Exception e) {
e.printStackTrace();
}
thanks to: System.out to a file in java
You should probably look into using a logging library such as Log4J. However you could also use something like a TeeOutputStream. This type of output stream writes to 2 other streams when called. A few libraries have great implementations but you can also write one yourself. I whipped this one up real quick.
You could set the output stream for your entire program in your main method to use this TeePrintStream, then all calls to System.out.* will write data to the usual System.out and your FileOutputStream.
Theres also an implementation of the TeePrintStream here http://www.java2s.com/Code/Java/File-Input-Output/TeePrintStreamteesallPrintStreamoperationsintoafileratherliketheUNIXtee1command.htm
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class SO34042494 {
public static void main(String[] args) throws FileNotFoundException {
System.setOut(new TeePrintStream(System.out, new FileOutputStream(new File("x:\\output.txt"))));
System.out.println("Check check");
System.out.println("1");
System.out.println(2);
System.out.println(3L);
}
public static class TeePrintStream extends PrintStream {
private final OutputStream tee;
public TeePrintStream(PrintStream original, OutputStream tee) {
super(original);
this.tee = tee;
}
#Override
public void write(byte[] b) throws IOException {
super.write(b);
tee.write(b);
}
#Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
try {
tee.write(buf, off, len);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#Override
public void write(int b) {
super.write(b);
try {
tee.write(b);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#Override
public synchronized void close() {
try {
tee.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
super.close();
}
}
}
}
The TeePrintStream I have here is something I just threw together, please if your going to use this in a production project polish it up and test it thoroughly
Okej i think i solved it. In my main i just did like this:
public static void main(String[] args) {
Prinstream out = new Prinststream(file);
/*
Do some things like start threads, call objects etc..
.
.
.
.
*/
System.setOut(out);
I think that when all threads are started and doing their things(i do assign a object to each thread) the printstream will catch every console-output that occurs in other classes.
This didn't work before i edited my stopExecute class.
public class stopExecute implements Runnable {
Scanner scan = new Scanner(System.in);
private Object[] obj;
public stopExecute(Object[] obj)
{
this.obj = obj;
}
public void run() {
while(true){
stop();
}
}
public void stop() {
if(scan.hasNextLine()){
System.out.println("Stopped");
System.exit(0);
}
}
}
Thank you for your help guys. I will look into your suggestions and try them. In this solution i'm unable to use Log4J. But i will definitely check it out.

Java Program Error saying class , interface or enum expected

import java.io.*;
public class Test13
{
public static void main(String[] args) throws IOException
{
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
int i;
while((i = sis.read())!=-1)
{
System.out.println((char)i);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
I think you tried something like that. I inserted some explenations to the Exception-Handling
import java.io.FileInputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
public class Test13 {
//because all exceptions are already catched main will never throw one
public static void main(String[] args) throws IOException {
try {
//if an exception raises anywhere from here ...
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
int i;
while ((i = sis.read()) != -1) {
System.out.println((char) i);
}
//... to here ...
} catch (Exception ex) {
//this catch block code will be executed
ex.printStackTrace();
}
}
}
You should have
try{
//function which throws exceptions
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
catch(Exception ex) {
// if a more general exception was thrown, handle it here
}
finally{
}
Below is the updated code and its working fine.
import java.io.*;
public class Test13
{
public static void main(String[] args) throws IOException {
try {
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
int i;
while ((i = sis.read()) != -1)
{
System.out.println((char) i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Categories

Resources