How to real time control how much of file should be read - java

I have a Text Class to read from File, Because of long time process I don't want to read from File in one moments! and have ListView that when scrolls read remains data from File.
How should I do it brothers and sisters?
Best Regards, Minallah Tofiq
public class MyText{
private AssetManager am;
private InputStream is ;
private BufferedReader br;
private String[] text;
private String Fulltext="";
private String linetext="";
public MyText(Context context,String FILE_URL) {
am = context.getAssets();
try {
is = am.open(FILE_URL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("READ", "cannot read from file");
}
br=new BufferedReader(new InputStreamReader(is));
}
public void process(){
try {
while((linetext=br.readLine())!= null){
Fulltext+=linetext;
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("ERROR", "can't read in process method");
e.printStackTrace();
}
text=Fulltext.split("\\d+");
}
public String[] returnString(){
return this.text;
}
}

You need to modify this line
while((linetext=br.readLine())!= null)
with an additional conditional. Such as
while((linetext=br.readLine())!= null && (/*your conditional here*/))

Related

Why i can't open second stream in java?

Here is my problem.I've made simple input class with methods for getting primitive values from user's keyboard.The problem is that whenever i use this class in my other classes i face the problem that when i made more than one instance of this class i get a problem of the "Close stream".Why is this happening?
For example:i have a main method where i get user's input and decide which object to make,say i can make 4 different objects(4 classes),after i call the objects "set state" method,where i actually set all the states of this object with making second instance of the input class,and then ,when i try to read again the user's input in my main method,i get an exception "Stream closed".
Here is the code of the input class :
public class UserInput {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));;
public int getInt() {
try {
String line;
line = reader.readLine();
return Integer.parseInt(line);
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
public double getDouble() {
try {
String line = reader.readLine();
return Double.parseDouble(line);
} catch (Exception ex) {
return -1;
}
}
public float getFloat() {
try {
String line = reader.readLine();
return Float.parseFloat(line);
} catch (Exception ex) {
return -1;
}
}
public long getLong() {
try {
String line = reader.readLine();
return Long.parseLong(line);
} catch (Exception ex) {
return -1;
}
}
public short getShort() {
try {
String line = reader.readLine();
return Short.parseShort(line);
} catch (Exception ex) {
return -1;
}
}
public String getString() {
try {
String line = reader.readLine();
return line;
} catch (Exception ex) {
return " ";
}
}
public char getChar() {
try {
return (char) reader.read();
} catch (Exception ex) {
return (' ');
}
}
public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The standard way for user input is to use a Scanner which already contains methods for reading different kinds of input.
You're not supposed to close the reader, because that will then close System.in which is not what you want.
By calling reader.close(); you are not only closing the reader himself because the call invokes the close() method of the InputStreamReader aswell and therefore closes System.in (which you can not reopen).
A possible Solution would be to use a Scanner as Kayaman pointed out in his answer or to override the close() method like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in){#Override public void close(){});

Stream closed error - Storm

I am trying to read a line in a file, in the spout, and then send it to the bolts but i keep getting a stream closed error. Do I close it wrong or what is the problem here?
public class InputSpout extends BaseRichSpout {
private SpoutOutputCollector collector;
public void
declareOutputFields( OutputFieldsDeclarer declarer) {
declarer.declare( new Fields("logfile"));
}
private FileReader fileReader;
private boolean completed = false;
private TopologyContext context;
#Override
public void open( Map config, TopologyContext context, SpoutOutputCollector collector) {
try {
this.context = context;
this.fileReader = new FileReader(("logfile.txt").toString());
} catch (FileNotFoundException e) {
throw new RuntimeException("Error reading file "
+ ("logfile"));
}
this.collector = collector;
}
public void nextTuple() {
if (completed) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
String str;
BufferedReader reader = new BufferedReader(fileReader);
str = null;
try {
str = reader.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
while (str != null) {
this.collector.emit(new Values(str));
str = reader.readLine();
}
} catch (Exception e) {
throw new RuntimeException("Error reading typle", e);
} finally {
completed = true;
}
try {
reader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
This is the error I am getting:
java.io.IOException: Stream closed
at sun.nio.cs.StreamDecoder.ensureOpen(StreamDecoder.java:46)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:147)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at myStorm.InputSpout.nextTuple(InputSpout.java:52)
at backtype.storm.daemon.executor$fn__4654$fn__4669$fn__4698.invoke(executor.clj:565)
at backtype.storm.util$async_loop$fn__458.invoke(util.clj:463)
at clojure.lang.AFn.run(AFn.java:24)
at java.lang.Thread.run(Thread.java:745)
You're closing the InputStream used by fileReader in nextTuple making it unavailable for subsequent calls. There's no need to close this Reader - just close a single BufferedReader when all data has been read.

Program in java that reads data from a text file

date time kg
12/10/2013 00.00.01 1
13/11/2013 00.00.05 2
17/12/2013 00.00.90 5
21/12/2013 00.00.23 6
27/12/2013 00.00.43 9
I have these data in an txt file. I would like to make o program in java that would read these data. I ' ve written the code above but I have mistakes. Could someone help me? The data have space between each other.
import java.io*;
public class ReadTextfile{
public static void main (String[] args) {
File file = new File ("test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
}
catch (IOException e) {
e.printStackTrace();
catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
boy you are only having some syntax problem
1 : replace
import java.io* with import java.io.*
2 : take care of your catch body being started and closed properly
try
{
// your code
}
catch(Exception e)
{
}
here is the working code , compare your program
import java.io.*;
public class ReadTextfile{
public static void main (String[] args)
{
File file = new File ("C:/Users/hussain.a/Desktop/test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
catch (FileNotFoundException e)
This is unreachable code, since above it you caught IOException.
Note that:
public class FileNotFoundException extends IOException
Your code won't compile. Remove this catch (You didn't even close it..)
Another thing, if this is not a type, you should replace java.io* with import java.io.*.
I would take the following approach:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadTextFile
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
List<Result> results = new ArrayList<Result>();
while(scanner.hasNextLine())
{
String currentLine = scanner.nextLine();
String [] resultArray = currentLine.split(" ");
results.add(new Result(resultArray[0], resultArray[1], resultArray[2]));
}
scanner.close();
}
private static class Result
{
private String date;
private String time;
private String kg;
public Result(String date, String time, String kg)
{
super();
this.date = date;
this.time = time;
this.kg = kg;
}
public String getDate()
{
return date;
}
public String getTime()
{
return time;
}
public String getKg()
{
return kg;
}
}
}
Now you can pull out any information that you want to from the list of results that you have.
So if you wanted to print everything, you could do the following:
for(Result singleResult : results)
{
System.out.println(singleResult.getDate() + " " + singleResult.getTime() + " " + singleResult.getKg());
}
You basically can do whatever you want to with the data. This approach would also allow you to transform the data into different types before you even create the Result object.

ObjectOutputStream, ObjectInputStream, and headers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to understand object serialization better, so I am practicing with some code I got from my textbook. (My textbook doesn't explain how to read and write/append objects to a serialization file every time the program starts, which is what I need to do.) I took their program, which just overwrites existing data in a file with the objects from the current session, and add code to it so that it will append the objects and read the whole file instead. I found something really useful here: Appending to an ObjectOutputStream but even if I create a subclass of ObjectOutputStream, override the writeStreamHeader method, and call this subclass if the file already exists, which is what they did, it still throws a CorruptedStreamException. My guess is that I would need to set the pointer back to the beginning of the file, but that doesn't seem to be necessary as there is only one ObjectOutputStream. So, my question is, what else could I possibly need to do?
EDIT: Here is some code.
WriteData.java
import java.io.*;
import java.util.Scanner;
public class WriteData
{
private int number;
private String name;
private float money;
private ObjectInputStream testopen;
private ObjectOutputStream output; //This is for the output. Make sure that
//this object gets an instance of FileOutputStream so that it can write objects
//to a FILE.
private AppendObjectOutputStream appendobjects;
static Scanner input = new Scanner(System.in);
static DataClass d;
public void openfile()
{
//Try opening a file (it must have the ".ser" extension).
try
{
//output = new ObjectOutputStream(new FileOutputStream("test.ser"));
testopen = new ObjectInputStream(new FileInputStream("test.ser"));
}
//If there is a failure, throw the necessary error.
catch (IOException exception)
{
try
{
output = new ObjectOutputStream(new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end case createfile
if (testopen != null)
{
try
{
testopen.close();
appendobjects = new AppendObjectOutputStream(
new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writedata()
{
//write the data until the user enters a sentry value.
System.out.println("Enter CTRL + z to stop input.\n");
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
while (input.hasNext())
{
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
try
{
number = input.nextInt();
name = input.next();
money = input.nextFloat();
//Make object with that data
d = new DataClass(number, name, money);
//write it to the file
if (output != null)
{
output.writeObject(d);
}
else if (appendobjects != null)
{
appendobjects.writeObject(d);
}
}
catch (IOException e)
{
System.out.println("Error writing to file.");
return;
}
}
System.out.println("\n");
} //end writedata
public void closefile()
{
try
{
if (output != null)
{
output.close();
}
else if (appendobjects != null)
{
appendobjects.close();
}
}
catch (IOException e)
{
System.out.println("Error closing file. Take precautions");
System.exit(1);
}
}
}
DataClass.java
import java.io.Serializable;
public class DataClass implements Serializable
{
private int someint;
private String somestring;
private float somefloat;
public DataClass(int number, String name, float amount)
{
setint(number);
setstring(name);
setfloat(amount);
}
public void setint(int i)
{
this.someint = i;
}
public int getint()
{
return someint;
}
public void setstring(String s)
{
this.somestring = s;
}
public String getstring()
{
return somestring;
}
public void setfloat(float d)
{
this.somefloat = d;
}
public float getfloat()
{
return somefloat;
}
}
AppendObjectOutputStream.java
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
public class AppendObjectOutputStream extends ObjectOutputStream
{
public AppendObjectOutputStream(FileOutputStream arg0) throws IOException
{
super(arg0);
// TODO Auto-generated constructor stub
}
//This is a function that is default in ObjectOutputStream. It just writes the
//header to the file, by default. Here, we are just going to reset the
//ObjectOutputStream
#Override
public void writeStreamHeader() throws IOException
{
reset();
}
}
ReadData.java
import java.io.*;
import java.util.Scanner;
public class ReadData
{
private FileInputStream f;
private ObjectInputStream input; //We should the constructor for this
//object an object of FileInputStream
private Scanner lines;
public void openfile()
{
try
{
f = new FileInputStream("test.ser");
input = new ObjectInputStream (f);
//input.reset();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void readdata()
{
DataClass d;
System.out.printf("%-15s%-12s%10s\n", "Account Number", "First Name",
"Balance");
try
{
while (true)
{
d = (DataClass)input.readObject(); //define d
//read data in from d
System.out.printf("%-15d%-12s%10.2f\n", d.getint(), d.getstring(),
d.getfloat());
}
}
catch (EOFException eof)
{
return;
}
catch (ClassNotFoundException e)
{
System.err.println("Unable to create object");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void closefile()
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException ex)
{
System.err.println("Error closing file.");
System.exit(1);
}
}
}
SerializationTest.java
public class SerializationTest
{
public static void main(String[] args)
{
ReadData r = new ReadData();
WriteData w = new WriteData();
w.openfile();
w.writedata();
w.closefile();
r.openfile();
r.readdata();
r.closefile();
}
}
I suggest to do it this way
ObjectOutputStream o1 = new ObjectOutputStream(new FileOutputStream("1"));
... write objects
o1.close();
ObjectOutputStream o2 = new AppendingObjectOutputStream(new FileOutputStream("1", true));
... append objects
o2.close();
it definitely works.
import EJP;
import Evgeniy_Dorofeev;
public class answer
{
private String answera, answerb;
public answer(String a, String b)
{
answera = a;
answerb = b;
}
public void main(String[] args)
{
answer(EJP.response(), Evgeniy_Dorofeev.response());
System.out.println(answera + '\n' + answerb);
}
}
You need to add a 'true' for the append parameter of new FileOutputStream() in the case where you are appending. Otherwise you aren't. Appending, that is.

Using IO Streams in Java

I need to launch a binary file using Java and then interact with it using input and output streams. I've written a prototype to figure out how it works, but so far the only output I'm getting has been null. When run on its own however the child program produces output. What am I doing wrong?
import java.io.*;
public class Stream {
public static void main(String args[]) {
Process SaddleSumExec = null;
BufferedReader outStream = null;
BufferedReader inStream = null;
try {
SaddleSumExec = Runtime.getRuntime().exec("/home/alex/vendor/program weights.txt list.txt");
}
catch(IOException e) {
System.err.println("Error on inStream.readLine()");
e.printStackTrace();
}
try {
inStream = new BufferedReader(new InputStreamReader
(SaddleSumExec.getInputStream()));
System.out.println(inStream.readLine());
}
catch(IOException e){
System.out.println("Error.");
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Prompt {
//flag to end readers and writer
boolean processEnd = false;
public static void main(String[] args) {
new Prompt();
}
public Prompt() {
Process SaddleSumExec = null;
Input in = new Input(this);
Output out = new Output(this);
Input err = new Input(this);
//thread to read a write console
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
Thread t3 = new Thread(err);
try {
SaddleSumExec = Runtime
.getRuntime()
.exec(
"ConsoleApplication1/bin/Debug/ConsoleApplication1");
in.input = SaddleSumExec.getInputStream();
err.input = SaddleSumExec.getErrorStream();
out.out = SaddleSumExec.getOutputStream();
t2.start();
t1.start();
t3.start();
SaddleSumExec.waitFor();
processEnd = true;
} catch (IOException e) {
System.err.println("Error on inStream.readLine()");
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean isProcessEnd() {
return processEnd;
}
public void setProcessEnd(boolean processEnd) {
this.processEnd = processEnd;
}
/*Readers of Inputs*/
class Input implements Runnable {
private BufferedReader inStream;
InputStream input;
Prompt parent;
public Input(Prompt prompt) {
// TODO Auto-generated constructor stub
parent = prompt;
}
public void run() {
inStream = new BufferedReader(new InputStreamReader(input));
while (!parent.isProcessEnd()) {
try {
String userInput;
while ((userInput = inStream.readLine()) != null) {
System.out.println(userInput);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/*Writers of Output*/
class Output implements Runnable {
OutputStream out;
Prompt parent;
public Output(Prompt prompt) {
parent = prompt;
// TODO Auto-generated constructor stub
}
#Override
public void run() {
while (!parent.isProcessEnd()) {
try {
String CurLine = "";
InputStreamReader converter = new InputStreamReader(
System.in);
BufferedReader in = new BufferedReader(converter);
while (!(CurLine.equals("quit"))) {
CurLine = in.readLine();
if (!(CurLine.equals("quit"))) {
out.write((CurLine + "\n").getBytes());
out.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You don't seem to be waiting for the child process to end so it is possible that the parent process ends before it gets a chance to read the output stream.
Here is an old but excellent article around Runtime.exec
http://www.javaworld.com/jw-12-2000/jw-1229-traps.html
The correct implementation is on this page
http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=4
From what I can tell - there could be two problems here :
Are you trying to obtain the access to the stream BEFORE the child program has started reading ?
Are you running the parent process with insufficient access rights?
If you read a null from readLine() it means the peer has closed the stream. There was no output.

Categories

Resources