We have to parse xml info from a generator that creates fake weather data for a bunch of weatherstations. Currently we're just printing it, but we'll have to do stuff with it later.
However, the data we receive consists of multiple XML "files". Is there a way to separate the data and split it at a new <?xml...?>? (The data is a continuous stream that randomly splits)
our code:
public class Main {
static private final int portNumber = Null;
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
BufferedReader clientReader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(clientReader);
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT) {
try {
String text = reader.getElementText();
System.out.println("Element Local Name:" + reader.getLocalName());
System.out.println("Text:" + text);
} catch (XMLStreamException e) {
System.out.println(e);
}
}
else if(event == XMLStreamConstants.END_ELEMENT){
reader.close();
}
}
} catch (IOException e) {
System.out.println("Error: Unable to Start Server Socket\n\t" + e);
} catch (XMLStreamException e){
System.out.println(e);
}
}
}
example of the xml (of which we receive multiple after each other):
<?xml version="1.0"?>
<!-- The WEATHERDATA-element contains multiple MEASUREMENT-elements -->
<WEATHERDATA>
<MEASUREMENT>
<STN>123456</STN>
<DATE>2009-09-13</DATE>
<TIME>15:59:46</TIME>
<TEMP>-60.1</TEMP>
<DEWP>-58.1</DEWP>
<STP>1034.5</STP>
<SLP>1007.6</SLP>
<VISIB>123.7</VISIB>
<WDSP>10.8</WDSP>
<PRCP>11.28</PRCP>
<SNDP>11.1</SNDP>
<FRSHTT>010101</FRSHTT>
<CLDC>87.4</CLDC>
<WNDDIR>342</WNDDIR>
</MEASUREMENT>
</WEATHERDATA>
We also have a dtd file but I'm not sure if that's helpful.
Using java.util.Scanner may serve as a quick workaround. The disassemble() function skips the XML declaration if present and combines all characters up to and including the next closing </WEATHERDATA> tag into a `String'. The result is then passed to the callback which in this example converts XML into a POJO with JAXB.
What I don't like about Scanner is that it internally buffers the input stream so it is possible to lose the last message when the stream is closed.
public class DisassembleXml {
private static final int port = 8888;
private static final Pattern XML_DECL_PATTERN = Pattern.compile("<\\?xml.*?\\?>");
private static final Pattern DATA_PATTERN =
Pattern.compile(".*?</WEATHERDATA>\\s+", Pattern.DOTALL);
public static void main(String[] args) throws Exception {
final ServerSocket serverSocket = new ServerSocket(port);
System.out.printf("Listening on %d%n", serverSocket.getLocalPort());
final Socket clientSocket = serverSocket.accept();
System.out.printf("Processing from %s%n", clientSocket);
try (Reader sr = new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.ISO_8859_1))
{
disassemble(sr, new ConvertToPojoAndPrint());
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void disassemble(Reader reader, Consumer<String> xmlConsumer) {
final Scanner sc = new Scanner(reader).useDelimiter("\\Z");
try {
while (true) {
final String xml = sc
.skip(XML_DECL_PATTERN)
.findWithinHorizon(DATA_PATTERN, 0);
if (xml == null || xml.isEmpty())
break;
xmlConsumer.accept(xml);
}
}
catch (Exception e) {
throw new IllegalStateException("cannot interpret stream", e);
}
}
private static class ConvertToPojoAndPrint implements Consumer<String>
{
final JAXBContext jaxbContext;
final Unmarshaller unmarshaller;
ConvertToPojoAndPrint() throws JAXBException {
jaxbContext = JAXBContext.newInstance(WeatherData.class);
unmarshaller = jaxbContext.createUnmarshaller();
}
#Override
public void accept(String xml) {
try {
final WeatherData weatherData = (WeatherData) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("Another sample: " + weatherData);
}
catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
#XmlRootElement(name = "WEATHERDATA")
private static class WeatherData
{
#XmlElement(name = "MEASUREMENT")
Measurement measurement;
#Override
public String toString() { return "WeatherData{" + "measurement=" + measurement + '}'; }
}
private static class Measurement
{
#XmlElement(name = "STN")
String stn;
// ... skipping the rest of elements for brevity
#Override
public String toString() { return "Measurement{" + "stn='" + stn + '\'' + '}'; }
}
}
Related
I'm making code for a Server that has multiple clients that joins in it. Here's what the server's looks like.
public class Server {
private final ServerSocket serverSocket;
private static final int PORT = 9000;
private WaitingRoom wroom = new WaitingRoom();
public Server(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public void startServer() throws InterruptedException,Exception{
try {
int count = 0;
while (!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
System.out.println("A new client has connected!");
ClientHandler clientHandler = new ClientHandler(new Player(count),socket);
Thread thread = new Thread(clientHandler);
thread.start();
count++;
System.out.println(clientHandler.getPlayer().getNickname());
wroom.join(clientHandler.getPlayer());
}
} catch (IOException e) {
closeServerSocket();
}
}
public void closeServerSocket() {
try {
if(serverSocket != null)
serverSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException,InterruptedException,Exception{
ServerSocket serverSocket = new ServerSocket(PORT);
Server server = new Server(serverSocket);
server.startServer();
}
}
I've a class named ClientHandler that manages these clients in a thread for each, and i pass it also in the Player class because i will use it for things like: Send msg, Receive msg. That's the ClientHandler class:
public class ClientHandler implements Runnable {
public static ArrayList<ClientHandler> clientHandlers = new ArrayList<>();
private Player player;
private String nickname;
private Socket socket;
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
public ClientHandler(Player player,Socket socket) throws InterruptedException,Exception{
try {
this.socket = socket;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter= new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
nickname = this.bufferedReader.readLine();
player.init(nickname, this);
clientHandlers.add(this);
broadcastMessage("SERVER: " + nickname + " è entrato");
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
public Player getPlayer(){
return player;
}
public BufferedWriter getBufferedWriter(){
return bufferedWriter;
}
public BufferedReader getBufferedReader(){
return bufferedReader;
}
#Override
public void run() {
String messageFromClient;
while (socket.isConnected()) {
/* try {
// messageFromClient = bufferedReader.readLine();
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
break;
} */
}
}
public void broadcastMessage(String messageToSend) {
for (ClientHandler clientHandler : clientHandlers) {
try {
if (!clientHandler.nickname.equals(nickname)) {
clientHandler.bufferedWriter.write(messageToSend);
clientHandler.bufferedWriter.newLine();
clientHandler.bufferedWriter.flush();
}
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
}
private void writeToClient(String text) throws IOException{
bufferedWriter.write(text);
bufferedWriter.newLine();
bufferedWriter.flush();
}
public void removeClientHandler() {
clientHandlers.remove(this);
broadcastMessage("SERVER: " + nickname + " è uscito");
}
public void closeEverything(Socket socket, BufferedReader bufferedReader, BufferedWriter bufferedWriter) {
removeClientHandler();
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now, the problem is: if I want to create a class named "WaitingRoom" for let players to waint until the wait's done. Where and how could I instantiate it? Before the linked code, i was instantiating it in the ClientHandler, but it worked only for a client a time. Here's what i wrote for the WaitingRoom class:
public class WaitingRoom {
private final int MAXPLAYERS = 2;
private ArrayList<Player> players = new ArrayList<Player>();
public ArrayList<Player> getPlayers(){
return players;
}
public void join(Player player) throws IOException,InterruptedException,Exception{
while(!addPlayer(player)){
player.sendMsg("waiting for join");
TimeUnit.SECONDS.sleep(1);
}
waitStart(player);
}
public boolean addPlayer(Player player){
if (players.size() >= MAXPLAYERS) return false;
players.add(player);
return true;
}
public boolean removePlayer(int idPlayer){
for(Player player : players){
if(player.getId() == idPlayer){
players.remove(player);
return true;
}
}
return false;
}
public void waitStart(Player player) throws IOException,InterruptedException,Exception{
if(players.size() < MAXPLAYERS)
player.sendMsg("sei entrato nella stanza d'attesa");
while(players.size() < MAXPLAYERS){
player.sendMsg("(" + players.size() + "/2) in attesa di giocatori...");
TimeUnit.SECONDS.sleep(1);
}
player.sendMsg("Inizio Gioco");
Player[] players2 = new Player[MAXPLAYERS];
for(int i=0;i<MAXPLAYERS;i++){
players2[0] = new Player(players.get(i).getId()).init(players.get(i).getNickname(),players.get(i).getClientHandler());
}
new Gioco(players2);
cleanRoom();
}
public void cleanRoom(){
players.clear();
}}
it's a really basic concept for waiting room and I only need a place where user must to wait before a gameloop. For example i don't really need multiple wainting rooms, one is ok for me, maybe.
I'm trying to create an object in one class then use that object in another class but each time I try to use it it just says the value is null
Customer cus = new Customer();
ServerSocket s = null;
public AddCustomer() {
}
public void getCustomerDetail() {
String back = " ";
{
try {
s = new ServerSocket(5433);
} catch (IOException e) {
System.out.println("Error:" + e.getMessage());
System.exit(0);
}
while (back.equals(" ")) {
try {
Socket s1 = s.accept();
System.out.println("Connection established at port 5433");
InputStream is = s1.getInputStream();
ObjectInputStream dis = new ObjectInputStream(is);
System.out.println("Getting data...");
cus = (Customer)dis.readObject();
System.out.println(cus.toString());
System.out.println(cus.getName());
dis.close();
s1.close();
System.out.println("Connection closed.");
} catch (ConnectException connExcep) {
System.out.println("1Error: " + connExcep.getMessage());
} catch (IOException ioExcep) {
System.out.println("2Error: " + ioExcep.getMessage());
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
}
}
}
public void addCustomerToDB() {
System.out.println("start ");
Connection connection = null;
Statement statement = null;
int check = 1;
System.out.println(cus.getName()+"dadawd");
}
When I print out the value of cus.getName() it just gives me null but when I print it out in getCustomerDetail it gives me the correct value.
dis.readObject returns an object with the values in it.
Depends on what you are doing in the getName function and in the constructor.
Maybe in getCustomerDetails() you are setting the values in the input stream. But the default constructor doesn't do anything with name variable.
It looks like the issue of packaging. Try below code.
public class AddCustomer {
public static void main(String[] args) {
new AddCustomer().getCustomerDetail();
}
Customer cus = new Customer();
public void getCustomerDetail() {
String back = " ";
{
while (back.equals(" ")) {
try {
System.out.println(cus.toString());
System.out.println(cus.getName());
System.out.println("Connection closed.");
} catch (Exception e) {
System.out.println("3Error: " + e.getMessage());
}
new AddCustomer().addCustomerToDB();
break;
}
}
}
public void addCustomerToDB() {
System.out.println(cus.getName()+"dadawd");
}
}
class Customer{
private String name="ABC";
String getName() {
return name;
}
}
We found here one issue you have to create "Customer cus = new Customer();" this object under main() function like as
public class AddCustomer {
public static void main(String[] args) {
Customer cus = new Customer();
new AddCustomer().getCustomerDetail();
}
Context
I made a Java application, and need to run two instances of that application, synchronizing some of their attributes via socket each time there's some change. To communicate those changes, Serializable objects are sent through a socket using ObjectStreams (input and output) using read/writeUTF() for an identifier, and read/writeObject() and flush(). The app is the exact same .jar, run twice with some changes like having different ports and ip (if necessary).
Problem
I noticed that objects of some of my classes (e.g. Notification) were sent and received without any troubles, but objects from another class (RegisteredUsers) weren't sent (or received) properly. So I ran some tests to send objects between the two apps and found that the object is being sent and isn't null, it's attribute (a HashMap<String,User>) is also being sent and isn't null, but is always empty.
So I decided to scale it down to what the problem was exactly: I'm trying to write an object through a Stream, and read it in a different process of the same .jar, and with most classes it seems to work, but it doesn't with one.
There seems to be something I'm missing or don't understand about this serialization process, if the object is written and read during the execution of the same process it works, but not if this object is read on another instance of the same app. I even added a HashMap to Notification with the same creation process, but it still works, I really don't get it, what am I missing?
Code
I have taken some code from the bigger app and trimmed it down to the basic problem if anyone wants to test it. To reproduce the errors, run Main1, which will create the two files with an object persisted in each one (one with a Notification object and the other with a RegisteredUsers object) and shows their information, then Main2, which reads them from the files and shows their information, and the problem should be printed. That being that reg3's HashMap is empty and thus neither of the Users are registered.
Main1
public class Main1 {
public static void main(String[] args) {
String regFile = "registry.txt";
String notificationFile = "notification.txt";
Persistence pers = new Persistence();
RegisteredUsers reg1 = new RegisteredUsers();
RegisteredUsers reg2 = new RegisteredUsers();
reg1.register("Name1", "127.0.0.1");
reg1.register("Name2", "127.0.0.1");
try {
pers.writeReg(reg1, regFile);
} catch (IOException e) {
System.out.println("Error writing registry.");
}
try {
reg2 = pers.readReg(regFile);
} catch (IOException e) {
System.out.println("Error reading registry.");
}
System.out.println("Original registry: ");
System.out.println(reg1.isRegistered("Name1") + " " + reg1.isRegistered("Name2"));
System.out.println("Registry read from file: ");
System.out.println(reg2.isRegistered("Name1") + " " + reg2.isRegistered("Name2"));
Notification noti1 = new Notification("Name", "127.0.0.1");
Notification noti2 = new Notification(); //not necesary but it's the way it's done in the bigger app.
try {
pers.writeNotif(noti1, notificationFile);
} catch (IOException e) {
System.out.println("Error writing notification.");
}
try {
noti2 = pers.readNotif(notificationFile);
} catch (IOException e) {
System.out.println("Error reading notification.");
}
System.out.println("Original notification: ");
System.out.println(noti1.getAttributes().get(0) + " " + noti1.getAttributes().get(1));
System.out.println(noti1.getMap());
System.out.println("Notification read from file: ");
System.out.println(noti2.getAttributes().get(0) + " " + noti2.getAttributes().get(1));
System.out.println(noti2.getMap());
}
}
Main2
public class Main2 {
public static void main(String[] args) {
String regFile = "registry.txt";
String notificationFile = "notification.txt";
Persistence pers = new Persistence();
RegisteredUsers reg3 = new RegisteredUsers();
try {
reg3 = pers.readReg(regFile);
} catch (IOException e) {
System.out.println("Error reading registry.");
}
if (reg3 == null) {
System.out.println("reg3 is null");
}
if (reg3.getMap() == null)
System.out.println("reg3 has a null map");
if (reg3.getMap().isEmpty())
System.out.println("reg3 has an empty map");
System.out.println("Registry read from file on another process: ");
System.out.println(reg3.isRegistered("Name1") + " " + reg3.isRegistered("Name2"));
Notification noti3 = new Notification(); //not necesary but it's the way it's done in the bigger app.
try {
noti3 = pers.readNotif(notificationFile);
} catch (IOException e) {
System.out.println("Error reading notification.");
}
System.out.println("Notification read from file on another process: ");
System.out.println(noti3.getAttributes().get(0) + " " + noti3.getAttributes().get(1));
System.out.println(noti3.getMap());
}
}
A Class to persist the objects in the files:
public class Persistence {
public void writeReg(RegisteredUsers regus, String file) throws IOException {
try(FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(regus);
oos.flush();
}
}
public RegisteredUsers readReg(String file) throws IOException {
RegisteredUsers regus = null;
try(FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);) {
regus = (RegisteredUsers) ois.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Wrong class.");
}
return regus;
}
public void writeNotif(Notification regus, String file) throws IOException {
try(FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(regus);
oos.flush();
}
}
public Notification readNotif(String file) throws IOException {
Notification notif = null;
try(FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);) {
notif = (Notification) ois.readObject();
} catch (ClassNotFoundException e) {
System.out.println("Wrong class.");
}
return notif;
}
}
RegisteredUsers
public class RegisteredUsers implements Serializable {
private static HashMap<String, User> users;
public RegisteredUsers() {
users = new HashMap<String, User>();
}
public HashMap<String, User> getMap() {
return users;
}
public boolean isRegistered(String name) {
User us = users.get(name);
return us != null;
}
public void register(String name, String ip) {
users.put(name, new User(name, ip, false));
}
}
Notification
public class Notification implements Serializable {
private ArrayList<String> attributes;
private HashMap<String, User> map = new HashMap<>();
public Notification() {
}
public Notification(String name, String ip) {
attributes = new ArrayList<String>();
attributes.add(0, name);
attributes.add(1, ip);
map.put(ip, new User(name, ip, false));
}
public ArrayList<String> getAttributes() {
return attributes;
}
public HashMap<String, User> getMap() {
return map;
}
}
User
public class User implements Serializable {
private String name;
private String ip;
private boolean connection_state;
public User(String name, String ip, boolean connection_state) {
this.name = name;
this.ip = ip;
this.connection_state = connection_state;
}
}
In java static fields are implicitly transient, and transient fields are not serialized.
If you modify the RegisterdUsers to
public class RegisteredUsers implements Serializable {
private HashMap<String, User> users; // static modifier is removed
...
}
The serialization will work.
FileReader fileReader = null;
Object reader = null;
String dataRow = null;
fileReader = new FileReader(new File(fileLocation));
if (extension.equals("csv"))
{
reader = new CSVReader(fileReader);
}
else
{
reader = new BufferedReader(fileReader);
}
while (null != (dataRow = reader.readLine()))
{
...
}
The idea is to use different types depending on the file type in order to remove duplicated code. However, I get an error on the last line, since reader is type Object. Thanks for the help.
Maybe you could make 2 methods:
public String read(CSVReader c){
return c.readLine();
}
public String read(BufferedReader br){
return br.readLine();
}
Then, in your current code:
if(extension.equals("csv"))
dataRow = read(new CSVReader(fileReader));
else
dataRow = read(new BufferedReader(fileReader));
This overloading would remove the need for a wrapper class.
If you really want to use a wrapper class, I recommend having this somewhere:
public interface MyIO{
public String readLine();
}
public class MyBr extends BufferedReader implements MyIO{}
public class MyCSV extends CSVReader implements MyIO{}
Then, in your code:
MyIO reader;
if(extension.equals("csv"))
reader = new MyCSV(fileReader);
else
reader = new MyBr(fileReader);
You'd notice that both are the same number of lines of code and (in my opinion) the methods are easier to follow.
Just answering to point out that it is certainly possible to use generics even if your types are not cooperative. You'll just have to define specializations for each type separately. I'll just put a sketch in Java 8 here. Not sure what you mean by 'Proper way', there are pros and cons to everything...especially in Java.
Somewhat simpler way, putting generic code in a common superclass:
interface GenericExample {
interface InputGenericCode<Input> {
/**
* This is implemented in subtypes.
*
* #param x
* #return
*/
String readLine(Input x);
default void genericAlgorithm(Input x) {
// algorithm expressed generically here...
for (;;) {
String lineString = readLine(x);
System.out.println("" + lineString);
}
}
}
public class BufferedReaderInputGenericCode implements InputGenericCode<BufferedReader> {
#Override
public String readLine(BufferedReader x) {
try {
return x.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public class CSVReaderInputGenericCode implements InputGenericCode<CSVReader> {
#Override
public String readLine(CSVReader x) {
return x.readLine();
}
}
static class CSVReader {
public CSVReader(FileReader fileReader) {
throw new RuntimeException("implement this");
}
public String readLine() {
throw new RuntimeException("implement this");
}
}
public static void main(String fileLocation, String extension) {
FileReader fileReader = openFile(fileLocation);
if (extension.equals("csv")) {
CSVReader reader = new CSVReader(fileReader);
new CSVReaderInputGenericCode().genericAlgorithm(reader);
} else {
BufferedReader reader = new BufferedReader(fileReader);
new BufferedReaderInputGenericCode().genericAlgorithm(reader);
}
// dataRow = reader.readLine();
}
public static FileReader openFile(String fileLocation) {
FileReader fileReader = null;
try {
fileReader = new FileReader(new File(fileLocation));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
return fileReader;
}
}
More complex way:
interface GenericExample {
/**
* All generic operations.
*
* #author jonasn
*
* #param <Input>
*/
interface InputGenerics<Input> {
String readLine(Input x);
}
interface InputGenericCode {
public static <Input> void genericAlgorithm(Input x, InputGenerics<Input> generics) {
// algorithm expressed generically here...
for (;;) {
String lineString = generics.readLine(x);
System.out.println("" + lineString);
}
}
}
static class CSVReader {
public CSVReader(FileReader fileReader) {
// TODO Auto-generated constructor stub
}
public String readLine() {
throw new RuntimeException("not implemented");
}
}
public class CSVReaderInputGenerics implements InputGenerics<CSVReader> {
#Override
public String readLine(CSVReader x) {
return x.readLine();
}
}
public class BufferedReaderInputGenerics implements InputGenerics<BufferedReader> {
#Override
public String readLine(BufferedReader x) {
try {
return x.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
}
public static void main(String fileLocation, String extension) {
// String fileLocation = "whatever";
// String extension = "";
FileReader fileReader = null;
// Object reader = null;
String dataRow = null;
try {
fileReader = new FileReader(new File(fileLocation));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
if (extension.equals("csv"))
{
CSVReader reader = new CSVReader(fileReader);
InputGenericCode.genericAlgorithm(reader, new CSVReaderInputGenerics());
}
else
{
BufferedReader reader = new BufferedReader(fileReader);
InputGenericCode.genericAlgorithm(reader, new BufferedReaderInputGenerics());
}
// dataRow = reader.readLine();
}
}
I create a program as below to execute a linux (raspbian) command: "omxplayer".
But I don't know why I cannot get output from omxplayer as the time I type it into command line and hit Enter.But the output only show at the end of the video.
So I want to get the output immediately after I type "omxplayer [video_name]" and hit "Enter" in my program.
Just like the command line (terminal) work when I type directly into it in linux.
This is my code:
public class testprog {
public static void main(String args[]) throws IOException {
String in = "";
while(in!="exit")
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
in = reader.readLine();
runCommand(in);
}
}
public static void runCommand(String command)
{
String s;
Process p;
try {
System.out.println("run command " + command);
p = Runtime.getRuntime().exec(new String[]{"bash", "-c",command});
MyInputStreamReader reader1 = new MyInputStreamReader(p.getInputStream());
reader1.setTag("in");
reader1.start();
MyInputStreamReader reader2 = new MyInputStreamReader(p.getErrorStream());
reader2.setTag("in");
reader2.start();
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
class MyInputStreamReader extends Thread{
boolean isStop = false;
ReadEventHandler handler;
String tag;
InputStream in;
public MyInputStreamReader(InputStream in)
{
this.in = in;
}
public void setHandler(ReadEventHandler handler) {
this.handler = handler;
}
public void setTag(String tag)
{
this.tag = tag;
}
public void run()
{
byte[] buff = new byte[8192];
while (true) {
//String line;
try {
int len = in.read(buff);
if (len == -1)
{
return;
}
String line = new String(buff, 0, len);
if (handler!=null)
handler.onReceived(line);
System.out.println(tag +" " + line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void dispose()
{
this.isStop = true;
}
public interface ReadEventHandler
{
void onReceived(String line);
}
}
Any response is highly appreciated. Thanks
Did you checked this?
http://javedmandary.blogspot.com/2014/01/firing-up-raspberry-pi-omxplayer-using.html
I guess there is the code you're looking for.