Pipes

3 respostas
W

Pessoal,

estou tentando implementar um programa que cria uma thread que por sua vez conecta no banco de dados, faz uma query e monta um ArrayList com os dados. Queria passar esses dados para o programa que “chamou” a thread, o programa compila mas quando eu executo eu tenho esse erro :

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header
        at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
        at java.io.ObjectInputStream.<init>(Unknown Source)
        at readStringArray.main(Unknown Source)

Ai vai o meu codigo :

import java.io.*;
import com.myown.utils.database.*;
import java.sql.*;
import java.util.*;

public class readStringArray {
    
    public static void main(String[] args) throws Exception {
	
	// array de bytes para receber o objeto.
	byte[] receiver = new byte[2024];

	PipedInputStream in = new PipedInputStream();
	TProcessObjects tProcess = new TProcessObjects(in);
	
	// create and start the thread.
	Thread t1 = new Thread(tProcess);	
	t1.start();

	// reads the PipedInputStream and set into receiver.
	in.read(receiver);
	
	// getting the object.
	
	ObjectInputStream inObj = new ObjectInputStream(in);
	
	ArrayList data  = (ArrayList)inObj.readObject();
	
	// stop thread.
	t1.stop();
	
    }

}

class TProcessObjects implements Runnable {

    PipedOutputStream pOut;    

    byte[] objByte = new byte[2024];

    Connection con = null; 
    Statement smt = null;
    ResultSet rs = null ;     

    String[] fields = {"cod","nome","porcent"};
    
    ArrayList array = new ArrayList();

    public TProcessObjects(PipedInputStream pipeIn) throws Exception {
	
	// link PipedOutputStream to PipedInputStream
	pOut = new PipedOutputStream(pipeIn);

	// create a db connection .
	con = DBConnector.getConnection();
	smt = con.createStatement();	
	
    }
    
    public void run() {
	
	try { 
	    
	    rs = smt.executeQuery("select * from estados");
	    
	    // convert the ResultSet data to a String[][]
	    String[][] data = new ResultSet2ArrayString().convert(rs,fields);

	    // Arrat String to ArrayList.
	    for (int i = 0; i < data.length; i ++ ) { array.add(data[i]); } 
	
	    ObjectOutputStream obj = new ObjectOutputStream(pOut);
	    
	    // write my ArrayList array to ObjectArrayOutputStream.
	    obj.writeObject(array);
	    obj.flush();

	    
	} catch (Exception e) {
	    e.printStackTrace();
	}
	
    }

    public void stop() {
	
	try { 
	    rs.close();
	    smt.close();
	    con.close();
	} catch(Exception e) {
	    e.printStackTrace();
	}

    }
    

}

Alguem tem alguma ideia ?

Obrigado

//Daniel

3 Respostas

T

Não é exatamente assim que se usa um PipedInputStream. Vou dar um exemplo melhor (dica: você não precisaria usar o “in.read” que você codificou na classe “readStringArray”), mas é questão de escrevê-lo.

E por favor, não comece nomes de classes por minúsculas (padrões são um lixo, são uma camisa de força, inibem o processo criativo, não são considerados pelo compilador nem pelo computador, mas ajudam muito um pobre mortal como eu, que não sou um computador nem um compilador).
Eu olhei seu programa e achei que era o nome de um método.

T

Requer Java 5.0 ou superior para rodar, mas não há nada "misterioso" que dificulte sua compreensão.

import java.io.*;
import java.util.*;

class Producer implements Runnable {
	private OutputStream outs;
	public Producer (OutputStream pOuts) {
		outs = pOuts;
	}
	public void run () {
		ObjectOutputStream oos = null;
		Random r = new Random();
		try {
			oos = new ObjectOutputStream (outs);
			while (true) {
				List&lt;String[]&gt; stringList = new ArrayList&lt;String[]&gt;();
				int nArrays = r.nextInt (10);
				for (int i = 0; i &lt nArrays; ++i) {
					String[] array = new String [1 + r.nextInt(5)];
					for (int j = 0; j &lt array.length; ++j) {
						array [j] = i + &quot;,&quot; + j;
					}
					stringList.add (array);
				}
				// Vamos mandar continuamente um ArrayList&lt;String[]&gt;, e efetuar um "flush".
				oos.writeObject (stringList);
				oos.flush();
				oos.reset(); // isto serve para evitar um "memory leak"
				try { Thread.sleep (10); } catch (InterruptedException ex) { break; }
			}
			oos.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

class Consumer implements Runnable {
	private InputStream inps;
	public Consumer (InputStream pInps) {
		inps = pInps;
	}
	@SuppressWarnings ("unchecked")
	public void run () {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream (inps);
			while (true) {
				List&lt;String[]&gt; arrayList = null;
				try {
					arrayList = (List&lt;String[]&gt;)ois.readObject ();
				} catch (ClassNotFoundException ex) {
					ex.printStackTrace();
					break;
				}
				if (arrayList == null) {
					break;
				}
				System.out.println (&quot;Received an &quot; + arrayList.getClass().getName() + &quot; with &quot; + arrayList.size() + &quot; arrays&quot;);
				for (int i = 0; i &lt arrayList.size(); ++i) {
					System.out.printf (&quot;%d is a %s with %d elements%n&quot;, i, arrayList.get(i).getClass().getSimpleName(), arrayList.get(i).length);
					for (int j = 0; j &lt arrayList.get(i).length; ++j) {
						System.out.printf (&quot;%8s&quot;, arrayList.get(i)[j]);
					}
					System.out.println();
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}

class ProducerConsumer {
	public static void main(String[] args) {
		PipedOutputStream pos = new PipedOutputStream ();
		PipedInputStream pis = null;
		try {
			pis = new PipedInputStream (pos);
			Producer prod = new Producer (pos);
			Consumer cons = new Consumer (pis);
			new Thread (prod).start();
			new Thread (cons).start();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
W

Hummm desculpe por comecar nome de classe com minuscula, eu nao sou tao bom.
Bom, de qualquer forma valeu por dispor de tempo procurando exemplo na net pra postar alguma coisa, mas nao era bem isso que eu queria fazer.

Valeu a intencao.

//Daniel

Criado 4 de julho de 2007
Ultima resposta 5 de jul. de 2007
Respostas 3
Participantes 2