Search Results

Search found 94 results on 4 pages for 'datainputstream'.

Page 1/4 | 1 2 3 4  | Next Page >

  • How to change internal buffer size of DataInputStream

    - by Gaks
    I'm using this kind of code for my TCP/IP connection: sock = new Socket(host, port); sock.setKeepAlive(true); din = new DataInputStream(sock.getInputStream()); dout = new DataOutputStream(sock.getOutputStream()); Then, in separate thread I'm checking din.available() bytes to see if there are some incoming packets to read. The problem is, that if a packet bigger than 2048 bytes arrives, the din.available() returns 2048 anyway. Just like there was a 2048 internal buffer. I can't read those 2048 bytes when I know it's not the full packet my application is waiting for. If I don't read it however - it'll all stuck at 2048 bytes and never receive more. Can I enlarge the buffer size of DataInputStream somehow? Socket receive buffer is 16384 as returned by sock.getReceiveBufferSize() so it's not the socket limiting me to 2048 bytes. If there is no way to increase the DataInputStream buffer size - I guess the only way is to declare my own buffer and read everything from DataInputStream to that buffer? Regards

    Read the article

  • Why does DataInputStream not support integers?

    - by Jason
    I need to read in a list of numbers from a file, none of which are larger than 32767. Originally I was going to use the Scanner class to pull in the data, then I read about DataInputStream. This would work well for me, except that according to the API, it supports all primitive variables EXCEPT ints! Listed are longs, shorts, bytes, chars, booleans, ect, but no ints. I have no need for double precision from the incoming data. Is this a deliberate or unintentional oversight?

    Read the article

  • deprecated readLine() What to change?

    - by user1681751
    I'm trying to get this to work in the eclipse, but the "readLine" is striked through and a notice says it is depreciated, the code works, albeit not the "while ((var2 = var5.readLine()) != null) {" bit.. So I'm wondering how to fix it, a java beginner. String var2 = ""; HttpURLConnection var3 = null; DataOutputStream var4 = null; DataInputStream var5 = null; ...more code here.... try { var5 = new DataInputStream(var3.getInputStream()); while ((var2 = var5.readLine()) != null) { System.out.println("Server Response " + var2); ScreenShotHelper.mc.thePlayer.addChatMessage("\u00a7aSuccessfully uploaded screenshot! Direct link:"); ScreenShotHelper.mc.thePlayer.addChatMessage("\u00a7a" + var2); } var5.close(); }

    Read the article

  • print integer and array from file android

    - by vik
    i want to open a file and then calculate the integer and array value from file and print on the screen. i tried this but not working @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView av = new TextView(this); setContentView(av); try { String i = "abc.xyz"; InputStream in = assets.open(i); try { DataInputStream din = new DataInputStream(in); int value = din.readInt(); // print value on screen int[] arry = new int[1]; // print arry on screen how to do it int arry[1] = din.readInt(); } } finally { in.close(); } } catch (IOException e) { throw new PuzzleIOException(e); } av.setText(size); }

    Read the article

  • PWC1406: Servlet.service() threw exception java.io.IOException: Invalid chunk header When client se

    - by Nivek
    I am developing an application using J2ME to send the GPS coordinates received to the server and i am new to developing client server application. Everything works fine with the use of Nokia N97mini or E71. But when i tried it on HTC HD2, i get the exception from the server. I am using Netbeans 6.5.1 GlassFish V2 as Server. I have no idea why this error occurs only on the HTC HD2. Any help will be greatly appreciated. Thanks... Below is the error message: StandardWrapperValve[FindHospitalServlet]: PWC1406: Servlet.service() for servlet FindHospitalServlet threw exception java.io.IOException: Invalid chunk header at org.apache.coyote.http11.filters.ChunkedInputFilter.doRead(ChunkedInputFilter.java:171) at org.apache.coyote.http11.InternalInputBuffer.doRead(InternalInputBuffer.java:719) at org.apache.coyote.Request.doRead(Request.java:482) at org.apache.coyote.tomcat5.InputBuffer.realReadBytes(InputBuffer.java:342) at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:378) at org.apache.coyote.tomcat5.InputBuffer.readByte(InputBuffer.java:351) at org.apache.coyote.tomcat5.CoyoteInputStream.read(CoyoteInputStream.java:159) at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:320) at java.io.DataInputStream.readUTF(DataInputStream.java:572) at java.io.DataInputStream.readUTF(DataInputStream.java:547) at myPackage.FindHospitalServlet.doPost(FindHospitalServlet.java:28) at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579) at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263) at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214) at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380) at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265) at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106) Below is the code that i wrote to connect to the server: private void connectFindHospServlet() { String url = "http://172.22.190.13:8080/UpdateServlet/FindHospitalServlet"; StringBuffer sb = new StringBuffer(); String info = lat+"!"+lng+"!"; try { HttpConnection c = (HttpConnection) Connector.open(url); c.setRequestProperty("User-Agent","Profile/MIDP-2.0, Configuration/CLDC-1.0"); c.setRequestProperty("Content-Language","en-US"); c.setRequestMethod(HttpConnection.POST); DataOutputStream os = (DataOutputStream)c.openDataOutputStream(); os.writeUTF(info); os.flush(); os.close(); // Get the response from the servlet page. DataInputStream is =(DataInputStream)c.openDataInputStream(); int ch; sb = new StringBuffer(); while ((ch = is.read()) != -1) sb.append((char)ch); is.close(); c.close(); if(sb.toString().charAt(0) == 'n') { formDisplayResultFindHosp(); display.setCurrent(formDisplayResultFindHosp); } else { PlannerMain pm = new PlannerMain(); hospInfo = pm.getFindHospInfo(sb.toString().substring(0, sb.length()-2)); formDisplayResultFindHosp(hospInfo); display.setCurrent(formDisplayResultFindHosp); } } catch (Exception e) { System.out.println("Error recieve find user"); } } Any information needed to better help in understanding the problem, do let me know. I will try to provide as much as possible.

    Read the article

  • readUTF timeout

    - by Hassan Voyeau
    I am getting a timeout with the following code at readUTF. Any idea why? hc = (HttpConnection) Connector.open("http://twitter.com/statuses/user_timeline/" + username + ".json"); int rc = hc.getResponseCode(); if (rc != HttpConnection.HTTP_OK) { throw new IOException("HTTP response code: " + rc); } DataInputStream dataInputStream = hc.openDataInputStream(); String list = dataInputStream.readUTF();

    Read the article

  • Problem locating file in a classpath

    - by Gandalf StormCrow
    I'm trying to read in file content, ex : public void myMethod(){ FileInputStream fstream = new FileInputStream(fileLocation); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { .... .... ..... end while end method And I have at the begining of the class body private String fileLocation; and at the end of a class I have a getter and setter for it. Now I'm trying inject this file location from spring inside bean from this class and I specify the init-method of this class. But I get error cannot find the specified file as if its not on a classpath but it is inside war file? I'm building the project with maven and I put file in src/main/resources This is the error I get when trying to read file : Error: src\main\resources\ids.txt (The system cannot find the path specified) That is when I tried this : FileInputStream fstream = new FileInputStream("src\\main\\resources\\ids.txt"); how to reference the properly from the classpath? EDIT When I edit my code according to @BalusC solution , here is how it looks but I still get null error : ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream("src/main/resources/ids.txt"); // Get the object of DataInputStream BufferedReader br = new BufferedReader(new InputStreamReader(input)); String strLine; while ((strLine = br.readLine()) != null) { .... .... ..... end while end method

    Read the article

  • Reuse Client java Socket in a Java Server

    - by user1394983
    I'm devoloping an Java server two control an android online game. It's possible save the client socket of myserversocket.accept() in a variable in Client class? This are very util because this way, server can communicate with client when server wants and no when client contact server. My actual code are: import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.UUID; import sal.app.shared.Packet; public class Server { private ArrayList<GameSession> games = new ArrayList<GameSession>(); private ArrayList<Client> pendent_clients = new ArrayList<Client>(); private Packet read_packet= new Packet(); private Packet sent_packet = new Packet(); private Socket clientSocket = null; public static void main(String[] args) throws ClassNotFoundException{ ServerSocket serverSocket = null; //DataInputStream dataInputStream = null; //DataOutputStream dataOutputStream = null; ObjectOutputStream oos=null; ObjectInputStream ois=null; Server myServer = new Server(); try { serverSocket = new ServerSocket(7777); System.out.println("Listening :7777"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } while(true){ try { myServer.clientSocket = new Socket(); myServer.clientSocket = serverSocket.accept(); myServer.read_packet = new Packet(); myServer.sent_packet = new Packet(); oos = new ObjectOutputStream(myServer.clientSocket.getOutputStream()); ois = new ObjectInputStream(myServer.clientSocket.getInputStream()); //dataInputStream = new DataInputStream(clientSocket.getInputStream()); //dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); //System.out.println("ip: " + clientSocket.getInetAddress()); //System.out.println("message: " + ois.read()); //dataOutputStream.writeUTF("Hello!"); /*while ((myServer.read_packet = (Packet) ois.readObject()) != null) { myServer.handlePacket(myServer.read_packet); break; }*/ myServer.read_packet=(Packet) ois.readObject(); myServer.handlePacket(myServer.read_packet); //oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ if( myServer.clientSocket!= null){ /*try { //myServer.clientSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } /*if( ois!= null){ try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if( oos!= null){ try { oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ } } } public void handlePacket(Packet hp) throws IOException { if(hp.getOpCode() == 1) { registPlayer(hp); } } public void registPlayer(Packet p) throws IOException { Client registClient = new Client(this.clientSocket); this.pendent_clients.add(registClient); if(pendent_clients.size() == 2) { initAGame(); } else { ObjectOutputStream out=null; Packet to_send = new Packet(); to_send.setOpCode(4); out = new ObjectOutputStream(registClient.getClientSocket().getOutputStream()); out.writeObject(to_send); } } public void initAGame() throws IOException { Client c1 = pendent_clients.get(0); Client c2 = pendent_clients.get(1); Packet to_send = new Packet(); ObjectOutputStream out=null; GameSession incomingGame = new GameSession(c1,c2); games.add(incomingGame); to_send.setGameId(incomingGame.getGameId()); to_send.setOpCode(5); out = new ObjectOutputStream(c1.getClientSocket().getOutputStream()); out.writeObject(to_send); out = new ObjectOutputStream(c2.getClientSocket().getOutputStream()); out.writeObject(to_send); pendent_clients.clear(); } public Client getClientById(UUID given_id) { for(GameSession gs: games) { if(gs.getClient1().getClientId().equals(given_id)) { return gs.getClient1(); } else if(gs.getClient2().getClientId().equals(given_id)) { return gs.getClient2(); } } return null; } } With this code i got this erros: java.net.SocketException: Broken pipe at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:136) at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1847) at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1756) at java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1257) at java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1211) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1395) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158) at java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1547) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:333) at Server.initAGame(Server.java:146) at Server.registPlayer(Server.java:120) at Server.handlePacket(Server.java:106) at Server.main(Server.java:63) This error ocurre when second client connect and server try to send an Packet to previous client 1 in function initGame() in this code: out = new ObjectOutputStream(c1.getClientSocket().getOutputStream()); out.writeObject(to_send); my android code is this: package sal.app; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import sal.app.logic.DataBaseManager; import sal.app.shared.Packet; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class MultiPlayerWaitActivity extends Activity{ private DataBaseManager db; public void onCreate(Bundle savedInstanceState) { super.requestWindowFeature(Window.FEATURE_NO_TITLE); super.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.multiwaitlayout); db=DataBaseManager.getSalDatabase(this); db.teste(); try { db.createDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Socket socket = null; ObjectOutputStream outputStream = null; ObjectInputStream inputStream = null; //System.out.println("dadadad"); try { socket = new Socket("192.168.1.4", 7777); //Game = new MultiPlayerGame(new ServerManager("192.168.1.66"),new Session(), new Player("")); outputStream = new ObjectOutputStream(socket.getOutputStream()); inputStream = new ObjectInputStream(socket.getInputStream()); //dataOutputStream.writeUTF(textOut.getText().toString()); //textIn.setText(dataInputStream.readUTF()); Packet p = new Packet(); Packet r = new Packet(); p.setOpCode(1); outputStream.writeObject(p); /*try { r=(Packet)inputStream.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //while(true){ //dataInputStream = new DataInputStream(clientSocket.getInputStream()); //dataOutputStream = new DataOutputStream(clientSocket.getOutputStream()); //System.out.println("ip: " + clientSocket.getInetAddress()); //System.out.println("message: " + ois.read()); //dataOutputStream.writeUTF("Hello!"); /*while ((r= (Packet) inputStream.readObject()) != null) { handPacket(r); break; }*/ r=(Packet) inputStream.readObject(); handPacket(r); //oos.close(); //} /*System.out.println(r.getOpCode()); if(r.getOpCode() == 5) { this.finish(); }*/ } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*finally{ if (socket != null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (outputStream != null){ try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (inputStream != null){ try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }*/ //catch (ClassNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); //} catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void handPacket(Packet hp) { if(hp.getOpCode() == 5) { this.finish(); } this.finish(); } } Regards

    Read the article

  • Sending arbitrarily long string over Java TCP socket

    - by bibismcbryde
    I have an Android app that communicates over a TCP socket with a server I wrote. The method I'm using now to read and write output works fine for smaller strings (up to 60kB) but I get an exception thrown when the string is much longer than that. Here is the relevant part of what I have for the server and client: Server: DataInputStream dis = null; DataOutputStream dos = null; try { dis = new DataInputStream(server.getInputStream()); dos = new DataOutputStream(server.getOutputStream()); String input = ""; input = dis.readUTF(); handle_input info = new handle_input(input, id); String xml = info.handle(); dos.writeUTF(xml); server.close(); } Client: Socket socket = null; DataOutputStream dos = null; DataInputStream dis = null; Boolean result; try { socket = new Socket(ip, port); dos = new DataOutputStream(socket.getOutputStream()); dis = new DataInputStream(socket.getInputStream()); dos.writeUTF(the_text); String in = ""; while (in.equals("")) { in += dis.readUTF(); } } How can I modify it to deal with potentially enormous Strings? I've been looking around and can't seem to find a clear answer. Thanks.

    Read the article

  • how to redirect terminal contents to a jtextpane?

    - by sonu thomas
    hi.. I was trying to run a java class file using java code.The aim was to direct the executing sequence of the terminal of fedora 10 into a frame with a textpane. My code is: import java.io.DataInputStream; import java.io.IOException; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextPane; //import sun.reflect.ReflectionFactory.GetReflectionFactoryAction; public class file { /** * @param args */ /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub JDialog jj = new JDialog(); jj.setTitle("helllo"); String sssub1,sssub2,sssub3; String ss="C:/Users/sonu/Desktop/ourIDE/src/src/nn.java"; JPanel n = new JPanel(); jj.setContentPane(n); JTextPane tpn2=new JTextPane(); jj.getContentPane().add(tpn2); jj.setVisible(true); Runtime runtime; Process process; if(ss.indexOf(" ")==-1) { try { runtime= Runtime.getRuntime(); sssub1="/home/ss/Desktop/src/"; sssub2="nn"; process=runtime.exec("sh jrun.sh "+sssub1+" "+sssub2); DataInputStream data=new DataInputStream(process.getInputStream()); DataInputStream data_data=new DataInputStream(process.getErrorStream()); String s="",t=""; int ch; while((ch=data.read())!=-1){ s=s+(char)ch; } data.close(); while((ch=data_data.read())!=-1){ t=t+(char)ch; } data_data.close(); if(t.equals("")) { s+="\nNormal Termination."; tpn2.setText(s); } else tpn2.setText(t); }catch(Exception e){ System.out.println("Error executing file==>"+e);} } } } The content of **jrun.sh** is cd $1 java $2 When the content of **nn.java** was this: import java.io.*; class nn { public static void main(String[] ar)throws IOException { int i=90; BufferedReader dt = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter"); //i=Integer.parseInt(dt.readLine()); line--notable System.out.println("i="+i); } } It worked smoothly But when I remove the comment on line--notable,it gave me Textpane with no content. The problem is : I cant read an input from nn.java Kindly give me a solution... If i am able to: get the terminal pop up with executing the nn.class,and i am able to enter the input,then it will do... Thanks in advance...

    Read the article

  • java.net.SocketException: Software caused connection abort: socket write error

    - by npinti
    Hi guys, I am trying to send an image from a Java desktop application to a J2ME application. The problem is that I am getting this exception: java.net.SocketException: Software caused connection abort: socket write error I have looked around on the net, and although this problem is not that rare, I was unable to find a concrete solution. I am transforming the image into a byte array before transferring it. These are the methods found on the desktop application and on the J2ME respectively public void send(String ID, byte[] serverMessage) throws Exception { //Get the IP and Port of the person to which the message is to be sent. String[] connectionDetails = this.userDetails.get(ID).split(","); Socket sock = new Socket(InetAddress.getByName(connectionDetails[0]), Integer.parseInt(connectionDetails[1])); OutputStream os = sock.getOutputStream(); for (int i = 0; i < serverMessage.length; i++) { os.write((int) serverMessage[i]); } os.flush(); os.close(); sock.close(); } private void read(final StreamConnection slaveSock) { Runnable runnable = new Runnable() { public void run() { try { DataInputStream dataInputStream = slaveSock.openDataInputStream(); int inputChar; StringBuffer results = new StringBuffer(); while ( (inputChar = dataInputStream.read()) != -1) { results.append((char) inputChar); } dataInputStream.close(); slaveSock.close(); parseMessage(results.toString()); results = null; } catch(Exception e) { e.printStackTrace(); Alert alertMsg = new Alert("Error", "An error has occured while reading a message from the server:\n" + e.getMessage(), null, AlertType.ERROR); alertMsg.setTimeout(Alert.FOREVER); myDisplay.setCurrent(alertMsg, resultScreen); } } }; new Thread(runnable).start(); } I am sending the message across a LAN, and I have no problems when I send short text messages instead of images. Also, I used wireshark and it seems that the desktop application is only sending part of the message. Any help would be highly appreciated. Also, everything works on the J2ME simulator. Thanks.

    Read the article

  • How to get size of bytes?

    - by k80sg
    How do I obtain the number of bytes before allocating the byte size of the array 'handsize' as shown below as the incoming ByteArray data are sent in 3 different sizes. Thanks. BufferedInputStream bais = new BufferedInputStream(requestSocket.getInputStream()); DataInputStream datainput = new DataInputStream(bais); //need to read the number of bytes here before proceeding. byte[] handsize = new byte[bytesize]; datainput.readFully(handsize);

    Read the article

  • Test if file exists

    - by klaus-vlad
    Hi, I'm trying to open a file in android like this : try { FileInputStream fIn = context.openFileInput(FILE); DataInputStream in = new DataInputStream(fIn); BufferedReader br = new BufferedReader(new InputStreamReader(in)); if(in!=null) in.close(); } catch(Exception e) { } , but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.

    Read the article

  • Data not synchornizing java sockets

    - by Droid_Interceptor
    I am writing a auction server and client and using a class called BidHandler to deal with the bids another class AuctionItem to deal with the items for auction. The main problem I am having is little synchroization problem. Screen output of client server as can see from the image at 1st it takes the new bid and changes the value of the time to it, but when one the user enters 1.0 the item seems to be changed to that. But later on when the bid changes again to 15.0 it seems to stay at that price. Is there any reason for that. I have included my code below. Sorry if didnt explain this well. This is the auction client import java.io.*; import java.net.*; public class AuctionClient { private AuctionGui gui; private Socket socket; private DataInputStream dataIn; private DataOutputStream dataOut; //Auction Client constructor String name used as identifier for each client to allow server to pick the winning bidder public AuctionClient(String name,String server, int port) { gui = new AuctionGui("Bidomatic 5000"); gui.input.addKeyListener (new EnterListener(this,gui)); gui.addWindowListener(new ExitListener(this)); try { socket = new Socket(server, port); dataIn = new DataInputStream(socket.getInputStream()); dataOut = new DataOutputStream(socket.getOutputStream()); dataOut.writeUTF(name); while (true) { gui.output.append("\n"+dataIn.readUTF()); } } catch (Exception e) { e.printStackTrace(); } } public void sentBid(String bid) { try { dataOut.writeUTF(bid); } catch(IOException e) { e.printStackTrace(); } } public void disconnect() { try { socket.close(); } catch(IOException e) { e.printStackTrace(); } } public static void main (String args[]) throws IOException { if(args.length!=3) { throw new RuntimeException ("Syntax: java AuctionClient <name> <serverhost> <port>"); } int port = Integer.parseInt(args[2]); AuctionClient a = new AuctionClient(args[0],args[1],port); } } The Auction Server import java.io.*; import java.net.*; import java.util.*; public class AuctionServer { public AuctionServer(int port) throws IOException { ServerSocket server = new ServerSocket(port); while(true) { Socket client = server.accept(); DataInputStream in = new DataInputStream(client.getInputStream()); String name = in.readUTF(); System.out.println("New client "+name+" from " +client.getInetAddress()); BidHandler b = new BidHandler (name, client); b.start(); } } public static void main(String args[]) throws IOException { if(args.length != 1) throw new RuntimeException("Syntax: java AuctionServer <port>"); new AuctionServer(Integer.parseInt(args[0])); } } The BidHandler import java.net.*; import java.io.*; import java.util.*; import java.lang.Float; public class BidHandler extends Thread { Socket socket; DataInputStream in; DataOutputStream out; String name; float currentBid = 0.0f; AuctionItem paper = new AuctionItem(" News Paper ", " Free newspaper from 1990 ", 1.0f, false); protected static Vector handlers = new Vector(); public BidHandler(String name, Socket socket) throws IOException { this.name = name; this.socket = socket; in = new DataInputStream (new BufferedInputStream (socket.getInputStream())); out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); } public synchronized void run() { try { broadcast("New bidder has entered the room"); handlers.addElement(this); while(true) { broadcast(paper.getName() + paper.getDescription()+" for sale at: " +paper.getPrice()); while(paper.getStatus() == false) { String message = in.readUTF(); currentBid = Float.parseFloat(message); broadcast("Bidder entered " +currentBid); if(currentBid > paper.getPrice()) { paper.setPrice(currentBid); broadcast("New Higgest Bid is "+paper.getPrice()); } else if(currentBid < paper.getPrice()) { broadcast("Higgest Bid is "+paper.getPrice()); } else if(currentBid == paper.getPrice()) { broadcast("Higgest Bid is "+paper.getPrice()); } } } } catch(IOException ex) { System.out.println("-- Connection to user lost."); } finally { handlers.removeElement(this); broadcast(name+" left"); try { socket.close(); } catch(IOException ex) { System.out.println("-- Socket to user already closed ?"); } } } protected static void broadcast (String message) { synchronized(handlers) { Enumeration e = handlers.elements(); while(e.hasMoreElements()) { BidHandler handler = (BidHandler) e.nextElement(); try { handler.out.writeUTF(message); handler.out.flush(); } catch(IOException ex) { handler = null; } } } } } The AuctionItem Class class AuctionItem { String itemName; String itemDescription; float itemPrice; boolean itemStatus; //Create a new auction item with name, description, price and status public AuctionItem(String name, String description, float price, boolean status) { itemName = name; itemDescription = description; itemPrice = price; itemStatus = status; } //return the price of the item. public synchronized float getPrice() { return itemPrice; } //Set the price of the item. public synchronized void setPrice(float newPrice) { itemPrice = newPrice; } //Get the status of the item public synchronized boolean getStatus() { return itemStatus; } //Set the status of the item public synchronized void setStatus(boolean newStatus) { itemStatus = newStatus; } //Get the name of the item public String getName() { return itemName; } //Get the description of the item public String getDescription() { return itemDescription; } } There is also simple GUI to go with this that seems to be working fine. If anyone wants it will include the GUI code.

    Read the article

  • Traceroute comparison and statistics

    - by ben-casey
    I have a number of traceroutes that i need to compare against each other but i dont know the best way to do it, ive been told that hash maps are a good technique but i dont know how to implement them on my code. so far i have: FileInputStream fstream = new FileInputStream("traceroute.log"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; // reads lines in while ((strLine = br.readLine()) != null) { System.out.println(strLine); } and the output looks like this: Wed Mar 31 01:00:03 BST 2010 traceroute to www.bbc.co.uk (212.58.251.195), 30 hops max, 40 byte packets 1 139.222.0.1 (139.222.0.1) 0.873 ms 1.074 ms 1.162 ms 2 core-from-cmp.uea.ac.uk (10.0.0.1) 0.312 ms 0.350 ms 0.463 ms 3 ueaha1btm-from-uea1 (172.16.0.34) 0.791 ms 0.772 ms 1.238 ms 4 bound-from-ueahatop.uea.ac.uk (193.62.92.71) 5.094 ms 4.451 ms 4.441 ms 5 gi0-3.norw-rbr1.eastnet.ja.net (193.60.0.21) 4.426 ms 5.014 ms 4.389 ms 6 gi3-0-2.chel-rbr1.eastnet.ja.net (193.63.107.114) 6.055 ms 6.039 ms * 7 lond-sbr1.ja.net (146.97.40.45) 6.994 ms 7.493 ms 7.457 ms 8 so-6-0-0.lond-sbr4.ja.net (146.97.33.154) 8.206 ms 8.187 ms 8.234 ms 9 po1.lond-ban4.ja.net (146.97.35.110) 8.673 ms 6.294 ms 7.668 ms 10 bbc.lond-sbr4.ja.net (193.62.157.178) 6.303 ms 8.118 ms 8.107 ms 11 212.58.238.153 (212.58.238.153) 6.245 ms 8.066 ms 6.541 ms 12 212.58.239.62 (212.58.239.62) 7.023 ms 8.419 ms 7.068 ms what i need to do is compare this trace against another one just like it and look for the changes and time differences etc, then print a stats page.

    Read the article

  • commons-exec: hanging when I call executor.execute(commandLine);

    - by Stefan Kendall
    I have no idea why this is hanging. I'm trying to capture output from a process run through commons-exec, and I continue to hang. I've provided an example program to demonstrate this behavior below. import java.io.DataInputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.PumpStreamHandler; public class test { public static void main(String[] args) { String command = "java"; PipedOutputStream output = new PipedOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); CommandLine cl = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); DataInputStream is = null; try { is = new DataInputStream(new PipedInputStream(output)); exec.setStreamHandler(psh); exec.execute(cl); } catch (ExecuteException ex) { } catch (IOException ex) { } System.out.println("huh?"); } }

    Read the article

  • Problem when trying to connect to a desktop server from android on wifi

    - by thiagolee
    Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code. Running on Android package br.ufs.reconhecimento; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; /** * Sample code that invokes the speech recognition intent API. */ public class Reconhecimento extends Activity implements OnClickListener { static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; static final String LOG_VOZ = "UFS-Reconhecimento"; final int INICIAR_GRAVACAO = 01; int porta = 5158; // Porta definida no servidor int tempoEspera = 1000; String ipConexao = "172.20.0.189"; EditText ipEdit; /** * Called with the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate our UI from its XML layout description. setContentView(R.layout.main); // Get display items for later interaction ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak); speakButton.setPadding(10, 10, 10, 10); speakButton.setOnClickListener(this); //Alerta para o endereço IP AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.setTitle("IP");//+mainWifi.getWifiState()); ipEdit = new EditText(this); ipEdit.setText(ipConexao); alerta.setView(ipEdit); alerta.setMessage("Por favor, Confirme o endereço IP."); alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ipConexao = ipEdit.getText().toString(); Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } }); alerta.create(); alerta.show(); } /** * Handle the click on the start recognition button. */ public void onClick(View v) { if (v.getId() == R.id.btn_speak) { //startVoiceRecognitionActivity(); Log.d(LOG_VOZ, "Iniciando a próxima tela"); Intent recordIntent = new Intent(this, GravacaoAtivity.class); Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)"); startActivityForResult(recordIntent, INICIAR_GRAVACAO); Log.d(LOG_VOZ, "Gravação iniciada ..."); } } /** * Handle the results from the recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_VOZ, "Iniciando onActivityResult()"); if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) { String path = data.getStringExtra(GravacaoAtivity.RETORNO); conexaoSocket(path); } else Log.e(LOG_VOZ, "Resultado Inexperado ..."); } private void conexaoSocket(String path) { Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera); if(socket == null) return; try { DataOutputStream conexao = new DataOutputStream(socket.getOutputStream()); Log.d(LOG_VOZ, "Acessando arquivo ..."); File file = new File(path); DataInputStream arquivo = new DataInputStream(new FileInputStream(file)); Log.d(LOG_VOZ, "Iniciando Transmissão ..."); conexao.writeLong(file.length()); for(int i = 0; i < file.length(); i++) conexao.writeByte(arquivo.readByte()); Log.d(LOG_VOZ, "Transmissão realizada com sucesso..."); Log.d(LOG_VOZ, "Fechando a conexão..."); conexao.close(); socket.close(); Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso =============="); } catch (IOException e) { Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage()); // TODO Auto-generated catch block } } } class SocketOpener implements Runnable { private String host; private int porta; private Socket socket; public SocketOpener(String host, int porta) { this.host = host; this.porta = porta; socket = null; } public static Socket openSocket(String host, int porta, int timeOut) { SocketOpener opener = new SocketOpener(host, porta); Thread t = new Thread(opener); t.start(); try { t.join(timeOut); } catch(InterruptedException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage()); //TODO: Mensagem informativa return null; } return opener.getSocket(); } public void run() { try { socket = new Socket(host, porta); }catch(IOException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage()); //TODO: Mensagem informativa } } public Socket getSocket() { return socket; } } Running on the desktop Java: import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServidorArquivo { private static int porta = 5158; static String ARQUIVO = "voz.amr"; /** * Caminho que será gravado o arquivo de audio */ static String PATH = "/home/iade/Trabalho/lib/"; public static void main(String[] args) { int i = 1; try { System.out.println("Iniciando o Servidor Socket - Android."); ServerSocket s = new ServerSocket(porta); System.out.println("Servidor Iniciado com Sucesso..."); System.out.println("Aguardando conexões na porta: " + porta); while(true) { Socket recebendo = s.accept(); System.out.println("Aceitando conexão de nº " + i); new ThreadedHandler(recebendo).start(); i++; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); e.printStackTrace(); } } } class ThreadedHandler extends Thread { private Socket socket; public ThreadedHandler(Socket so) { socket = so; } public void run() { DataInputStream entrada = null; DataOutputStream arquivo = null; try { entrada = new DataInputStream(socket.getInputStream()); System.out.println("========== Iniciando a leitura dos dados via Sockets =========="); long tamanho = entrada.readLong(); System.out.println("Tamanho do vetor " + tamanho); File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO); if(!file.exists()) file.createNewFile(); arquivo = new DataOutputStream(new FileOutputStream(file)); for(int j = 0; j < tamanho; j++) { arquivo.write(entrada.readByte()); } System.out.println("========== Dados recebidos com sucesso =========="); } catch (Exception e) { System.out.println("Erro ao tratar do socket: " + e.getMessage()); e.printStackTrace(); } finally { System.out.println("**** Fechando as conexões ****"); try { entrada.close(); socket.close(); arquivo.close(); } catch (IOException e) { System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage()); e.printStackTrace(); } } System.out.println("============= Fim da Gravação ==========="); // tratar o arquivo String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav"; String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100"; String dir = "/home/iade/Trabalho/lib"; File workDir = new File(dir); File f1 = new File(dir+"/voz.wav"); File f2 = new File(dir+"/voz2.wav"); f1.delete(); f2.delete(); try { executeCommand(cmd1, workDir); System.out.println("realizou cmd1"); executeCommand(cmd2, workDir); System.out.println("realizou cmd2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void executeCommand(String cmd1, File workDir) throws IOException, InterruptedException { String s; Process p = Runtime.getRuntime().exec(cmd1,null,workDir); int i = p.waitFor(); if (i == 0) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } } else { BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdErr.readLine()) != null) { System.out.println(s); } } } } Thanks in advance.

    Read the article

  • Playing an Online mp3

    - by Mohsen
    I have a problem with playing online mp3s. I'm using latest version of javazoom's jlayer and basicplayer. Here is the exception: Caused by: javazoom.jlgui.basicplayer.BasicPlayerException: java.io.EOFException at javazoom.jlgui.basicplayer.BasicPlayer.initAudioInputStream(Unknown Source) at javazoom.jlgui.basicplayer.BasicPlayer.open(Unknown Source) ... 12 more Caused by: java.io.EOFException at java.io.DataInputStream.readInt(DataInputStream.java:375) at com.sun.media.sound.WaveFileReader.getFMT(WaveFileReader.java:244) at com.sun.media.sound.WaveFileReader.getAudioFileFormat(WaveFileReader.java:85) at javax.sound.sampled.AudioSystem.getAudioFileFormat(AudioSystem.java:985) at javazoom.jlgui.basicplayer.BasicPlayer.initAudioInputStream(Unknown Source) ... 15 more My java is 1.6.0_16. Certain files cannot be player through the Internet. I have a set of mp3s, playing one after the other. Randomly one mp3 doesn't work throwing above exception. Some mp3s can be played by calling again play() method if javazoom's basicplayer, but others can never be played online. I was able to find this post but I doubt if this really relates to my directx version or something. Mohsen

    Read the article

  • Additional spaces in String having read text file to String using FileInputStream

    - by David
    Hi, I'm trying to read in a text file to a String variable. The text file has multiple lines. Having printed the String to test the "read-in" code, there is an additional space between every character. As I am using the String to generate character bigrams, the spaces are making the sample text useless. The code is try{ FileInputStream fstream = new FileInputStream(textfile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); //Read corpus file line-by-line, concatenating each line to the String "corpus" while ((strLine = br.readLine()) != null) { corpus = (corpus.concat(strLine)); } in.close(); //Close the input stream } catch (Exception e) {//Catch exception if any System.err.println("Error test check: " + e.getMessage()); } I'd be grateful for any advice. Thanks.

    Read the article

  • capturing video from ip camera

    - by Ruby
    I am trying to capture video from ip camera into my application , its giving exception com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0x0d 0x0a at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method) at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(Unknown Source) at test.AxisCamera1.readJPG(AxisCamera1.java:130) at test.AxisCamera1.readMJPGStream(AxisCamera1.java:121) at test.AxisCamera1.readStream(AxisCamera1.java:100) at test.AxisCamera1.run(AxisCamera1.java:171) at java.lang.Thread.run(Unknown Source) its giving exception at image = decoder.decodeAsBufferedImage(); Here is the code i am trying private static final long serialVersionUID = 1L; public boolean useMJPGStream = true; public String jpgURL = "http://ip here/video.cgi/jpg/image.cgi?resolution=640×480"; public String mjpgURL = "http://ip here /video.cgi/mjpg/video.cgi?resolution=640×480"; DataInputStream dis; private BufferedImage image = null; public Dimension imageSize = null; public boolean connected = false; private boolean initCompleted = false; HttpURLConnection huc = null; Component parent; /** Creates a new instance of AxisCamera */ public AxisCamera1(Component parent_) { parent = parent_; } public void connect() { try { URL u = new URL(useMJPGStream ? mjpgURL : jpgURL); huc = (HttpURLConnection) u.openConnection(); // System.out.println(huc.getContentType()); InputStream is = huc.getInputStream(); connected = true; BufferedInputStream bis = new BufferedInputStream(is); dis = new DataInputStream(bis); if (!initCompleted) initDisplay(); } catch (IOException e) { // incase no connection exists wait and try // again, instead of printing the error try { huc.disconnect(); Thread.sleep(60); } catch (InterruptedException ie) { huc.disconnect(); connect(); } connect(); } catch (Exception e) { ; } } public void initDisplay() { // setup the display if (useMJPGStream) readMJPGStream(); else { readJPG(); disconnect(); } imageSize = new Dimension(image.getWidth(this), image.getHeight(this)); setPreferredSize(imageSize); parent.setSize(imageSize); parent.validate(); initCompleted = true; } public void disconnect() { try { if (connected) { dis.close(); connected = false; } } catch (Exception e) { ; } } public void paint(Graphics g) { // used to set the image on the panel if (image != null) g.drawImage(image, 0, 0, this); } public void readStream() { // the basic method to continuously read the // stream try { if (useMJPGStream) { while (true) { readMJPGStream(); parent.repaint(); } } else { while (true) { connect(); readJPG(); parent.repaint(); disconnect(); } } } catch (Exception e) { ; } } public void readMJPGStream() { // preprocess the mjpg stream to remove the // mjpg encapsulation readLine(3, dis); // discard the first 3 lines readJPG(); readLine(2, dis); // discard the last two lines } public void readJPG() { // read the embedded jpeg image try { JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(dis); image = decoder.decodeAsBufferedImage(); } catch (Exception e) { e.printStackTrace(); disconnect(); } } public void readLine(int n, DataInputStream dis) { // used to strip out the // header lines for (int i = 0; i < n; i++) { readLine(dis); } } public void readLine(DataInputStream dis) { try { boolean end = false; String lineEnd = "\n"; // assumes that the end of the line is marked // with this byte[] lineEndBytes = lineEnd.getBytes(); byte[] byteBuf = new byte[lineEndBytes.length]; while (!end) { dis.read(byteBuf, 0, lineEndBytes.length); String t = new String(byteBuf); System.out.print(t); // uncomment if you want to see what the // lines actually look like if (t.equals(lineEnd)) end = true; } } catch (Exception e) { e.printStackTrace(); } } public void run() { System.out.println("in Run..................."); connect(); readStream(); } @SuppressWarnings("deprecation") public static void main(String[] args) { JFrame jframe = new JFrame(); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); AxisCamera1 axPanel = new AxisCamera1(jframe); new Thread(axPanel).start(); jframe.getContentPane().add(axPanel); jframe.pack(); jframe.show(); } } Any suggestions what I am doing wrong here??

    Read the article

  • How do I recieve byteArray sent from a Server and read 4 single bytes at a time.

    - by k80sg
    I need to receive 320 bytes of data from a server which consist of 80 4 byte int fields. How do I receive them in bytes of 4 and display their respective int values? Thanks. Not sure if this is right for the receiving part: //for reading the data from the socket BufferedInputStream bufferinput=new BufferedInputStream(NewSocket.getInputStream()); DataInputStream datainput=new DataInputStream(bufferinput); byte[] handsize=new byte[32]; // The control will halt at the below statement till all the 32 bytes are not read from the socket. datainput.readFully(handsize);

    Read the article

  • How do I get Java to use my multi-core processor?

    - by Rudiger
    I'm using a GZIPInputStream in my program, and I know that the performance would be helped if I could get Java running my program in parallel. In general, is there a command-line option for the standard VM to run on many cores? It's running on just one as it is. Thanks! Edit I'm running plain ol' Java SE 6 update 17 on Windows XP. Would putting the GZIPInputStream on a separate thread explicitly help? No! Do not put the GZIPInputStream on a separate thread! Do NOT multithread I/O! Edit 2 I suppose I/O is the bottleneck, as I'm reading and writing to the same disk... In general, though, is there a way to make GZIPInputStream faster? Or a replacement for GZIPInputStream that runs parallel? Edit 3 Code snippet I used: GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(INPUT_FILENAME)); DataInputStream in = new DataInputStream(new BufferedInputStream(gzip));

    Read the article

  • How do I recieve byteArray send from Server and read 4 single bytes at a time.

    - by k80sg
    I need to receive 320 bytes of data from a server which consist of 80 4 bytes int fields. How do I receive them in bytes of 4 and display their respective int values? Thanks. Not sure if this is right for the receiving part: //for reading the data from the socket BufferedInputStream bufferinput=new BufferedInputStream(NewSocket.getInputStream()); DataInputStream datainput=new DataInputStream(bufferinput); byte[] handsize=new byte[32]; // The control will halt at the below statement till all the 32 bytes are not read from the socket. datainput.readFully(handsize);

    Read the article

  • Shouldn't ObjectInputStream extend FilterInputStream?

    - by Vaibhav Bajpai
    The block quotes are from the Java Docs - A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality. A DataInputStream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. The DataInputStream therefore extends FilterInputStream An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. However, for some reason the ObjectInputStream does NOT extend FilterInputStream even though it is also reading objects (this time and not primitive types) from the underlying input stream. Here is the branching of the concerned classes. Is there is a design reasoning for the same?

    Read the article

  • Java Compiler - Load Method

    - by Brian
    So I have been working on a java project where the goal is to create a virtual computer. So I am basically done but with one problem. I have created a compiler which translates a txt document with assembly code in it and my compiler has created a new-file with this code written as machine executable ints. But now I need to write a load method that reads these ints and runs the program but I am having difficulty doing this. Any help is much appreciated....also this is not homework if you are thinking this. The project was simply to make a compiler and now I am trying to complete it for my own interest. Thanks. Here is what I have so far for load: public void load(String filename) { FileInputStream fs = new FileInputStream(filename); DataInputStream dos = new DataInputStream(fs); dos.readInt();

    Read the article

1 2 3 4  | Next Page >