Search Results

Search found 561 results on 23 pages for 'inputstream'.

Page 2/23 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • getResourceAsStream returns HttpInputStream not of the entire file

    - by khue
    Hi, I am having a web application with an applet which will copy a file packed witht the applet to the client machine. When I deploy it to webserver and use: InputStream in = getClass().getResourceAsStream("filename") ; The in.available() always return a size of 8192 bytes for every file I tried, which means the file is corrupted when it is copied to the client computer. The InputStream is of type HttpInputStream (sun.net.protocol.http.HttpUrlConnection$httpInputStream). But while I test applet in applet viewer, the files are copied fine, with the InputStream returned is of type BufferedInputStream, which has the file's byte sizes. I guess that when getResourceStream in file system the BufferedInputStream will be used and when at http protocol, HttpInputStream will be used. How will I copy the file completely, is there a size limited for HttpInputStream? Thanks a lot.

    Read the article

  • Java InputStream encoding/charset

    - by Tobbe
    Running the following (example) code import java.io.*; public class test { public static void main(String[] args) throws Exception { byte[] buf = {-27}; InputStream is = new ByteArrayInputStream(buf); BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); String s = r.readLine(); System.out.println("test.java:9 [byte] (char)" + (char)s.getBytes()[0] + " (int)" + (int)s.getBytes()[0]); System.out.println("test.java:10 [char] (char)" + (char)s.charAt(0) + " (int)" + (int)s.charAt(0)); System.out.println("test.java:11 string below"); System.out.println(s); System.out.println("test.java:13 string above"); } } gives me this output test.java:9 [byte] (char)? (int)63 test.java:10 [char] (char)? (int)229 test.java:11 string below ? test.java:13 string above How do I retain the correct byte value (-27) in the line-9 printout? And consequently receive the expected output of the System.out.println(s) command (å).

    Read the article

  • Java equivalent of the VB Request.InputStream

    - by Android Addict
    I have a web service that I am re-writing from VB to a Java servlet. In the web service, I want to extract the body entity set on the client-side as such: StringEntity stringEntity = new StringEntity(xml, HTTP.UTF_8); stringEntity.setContentType("application/xml"); httppost.setEntity(stringEntity); In the VB web service, I get this data by using: Dim objReader As System.IO.StreamReader objReader = New System.IO.StreamReader(Request.InputStream) Dim strXML As String = objReader.ReadToEnd and this works great. But I am looking for the equivalent in Java. I have tried this: ServletInputStream dataStream = req.getInputStream(); byte[] data = new byte[dataStream.toString().length()]; dataStream.read(data); but all it gets me is an unintelligible string: data = [B@68514fec Please advise. Edit Per the answers, I have tried: ServletInputStream dataStream = req.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int r; byte[] data = new byte[1024*1024]; while ((r = dataStream.read(data, 0, data.length)) != -1) { buffer.write(data, 0, r); } buffer.flush(); byte[] data2 = buffer.toByteArray(); System.out.println("DATA = "+Arrays.toString(data2)); whichs yields: DATA = [] and when I try: System.out.println("DATA = "+data2.toString()); I get: DATA = [B@15282c7f So what am I doing wrong? As stated earlier, the same call to my VB service gives me the xml that I pass in.

    Read the article

  • How to send XML data through socket InputStream

    - by THeK3nger
    Hi, I'm trying to write a client-server application in Java with an XML-based protocol. But I have a great problem! See this part of client code: InputStream incoming = skt.getInputStream(); //I get Stream from Socket. OutputStream out = skt.getOutputStream(); [...] XMLSerializer serializer = new XMLSerializer(); //This create an XML document. tosend = WUTPClientWriter.createMessage100(projectid, cpuclock, cpunumber); serializer.setOutputByteStream(out); serializer.serialize(tosend); At this point server fall in deadlock. It wait for EOF but I can't send it because if I use out.close(); or skt.shutdownOutput(); I close Socket and I must keep alive this connection. I can't send '\0' becouse I get Parse Error in the server. How can I do? Can I "close" output stream without close socket? RESOLVED I've created new class XMLStreamOutput and XMLStreamInput with advanced Stream gesture.

    Read the article

  • How to remove accent characters from an InputStream

    - by Samuh
    I am trying to parse a Rss2.0 feed on Android using a Pull parser. XmlPullParser parser = Xml.newPullParser(); parser.setInput(url.open(), null); The prolog of the feed XML says the encoding is "utf-8". When I open the remote stream and pass this to my Pull Parser, I get invalid token, document not well formed exceptions. When I save the XML file and open it in the browser(FireFox) the browser reports presence of Unicode 0x12 character(grave accent?) in the file and fails to render the XML. What is the best way to handle such cases assuming that I do not have any control over the XML being returned? Thanks.

    Read the article

  • Pipe data from InputStream to OutputStream in Java

    - by Wangnick
    Dear all, I'd like to send a file contained in a ZIP archive unzipped to an external program for further decoding and to read the result back into Java. ZipInputStream zis = new ZipInputStream(new FileInputStream(ZIPPATH)); Process decoder = new ProcessBuilder(DECODER).start(); ??? BufferedReader br = new BufferedReader(new InputStreamReader( decoder.getInputStream(),"us-ascii")); for (String line = br.readLine(); line!=null; line = br.readLine()) { ... } What do I need to put into ??? to pipe the zis content to the decoder.getOutputStream()? I guess a dedicated thread is needed, as the decoder process might block when its output is not consumed.

    Read the article

  • Socket Programming : Inputstream Stuck in loop - read() always return 0

    - by Atom Skaa ska Hic
    Server side code public static boolean sendFile() { int start = Integer.parseInt(startAndEnd[0]) - 1; int end = Integer.parseInt(startAndEnd[1]) - 1; int size = (end - start) + 1; try { bos = new BufferedOutputStream(initSocket.getOutputStream()); bos.write(byteArr,start,size); bos.flush(); bos.close(); initSocket.close(); System.out.println("Send file to : " + initSocket); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); disconnected(); return false; } return true; } Client Side public boolean receiveFile() { int current = 0; try { int bytesRead = bis.read(byteArr,0,byteArr.length); System.out.println("Receive file from : " + client); current = bytesRead; do { bytesRead = bis.read(byteArr, current, (byteArr.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead != -1); bis.close(); bos.write(byteArr, 0 , current); bos.flush(); bos.close(); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); disconnected(); return false; } return true; } Client side is multithreading,server side not use multithreading. I just paste some code that made problem if you want see all code please tell me. After I debug the code, I found that if I set max thread to any and then the first thread always stuck in this loop. That bis.read(....) always return 0. Although, server had close stream and it not get out of the loop. I don't know why ... But another threads are work correctly. do { bytesRead = bis.read(byteArr, current, (byteArr.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead != -1);

    Read the article

  • How do I/O operations block?

    - by someguy
    I am specifically referring to InputStream (Java SE) and its implementations. How is blocking performed? I'm a little worried that they use a "busy-waiting" mechanism, as it would produce a lot of overhead. I believe they do it another way, but I'm just asking to be certain.

    Read the article

  • Java's getResourceAsStream() is always returning null

    - by Andreas Grech
    I have the following structure in a Java Web Application: TheProject -- [Web Pages] -- -- [WEB-INF] -- -- -- abc.txt -- -- index.jsp -- [Source Packages] -- -- [wservices] -- -- -- WS.java In WS.java, I am using the following code in a Web Method: InputStream fstream = this.getClass().getResourceAsStream("abc.txt"); But it is always returning a null. I need to read from that file, and I read that if you put the files in WEB-INF, you can access them with getResourceAsStream, yet the method is always returning a null. Any ideas of what I may be doing wrong?

    Read the article

  • Interrupt an Http Request blocked in read() on Android

    - by twk
    Using the Apache Http stack on Android, I'm trying to force a thread out of a call to read. This is what the stack looks like: OSNetworkSystem.receiveStreamImpl(FileDescriptor, byte[], int, int, int) line: not available [native method] OSNetworkSystem.receiveStream(FileDescriptor, byte[], int, int, int) line: 478 PlainSocketImpl.read(byte[], int, int) line: 565 SocketInputStream.read(byte[], int, int) line: 87 SocketInputBuffer(AbstractSessionInputBuffer).fillBuffer() line: 103 SocketInputBuffer(AbstractSessionInputBuffer).read(byte[], int, int) line: 134 IdentityInputStream.read(byte[], int, int) line: 86 EofSensorInputStream.read(byte[], int, int) line: 159 Fetcher.readStream() line: 89 I've tried InputStream.close(), Thread.Interrupt(), and HttpUriRequest.abort(), without any success. Any ideas? I'm also open to some kind of non-blocking IO, but I don't see any way to do that with the HttpUriRequest object. Thanks!

    Read the article

  • How to get server message correctly

    - by Leo
    Problem I send the message "12345" from the socket server to the client: myPrintWriter.println("12345"); After that I read this message on client: int c; while ((c = inputStream.read( )) != -1) { byte[] buffer2 = new byte[1]; buffer2[0] = (byte) c; String symbol = new String(buffer2 , "UTF-8"); String symbolCode = Integer.toString((int)buffer2[0]); Log.v(symbol, symbolCode); } Log.v("c == -1", "Disconnected"); What I see in log: With out.println("abcrefg"); Why? I think it's line termination symbol. I need to get string "12345" or any other and next strings correctly. Help me please.

    Read the article

  • getResourceAsStream() is always returning null

    - by Andreas Grech
    I have the following structure in a Java Web Application: TheProject -- [Web Pages] -- -- [WEB-INF] -- -- -- abc.txt -- -- index.jsp -- [Source Packages] -- -- [wservices] -- -- -- WS.java In WS.java, I am using the following code in a Web Method: InputStream fstream = this.getClass().getResourceAsStream("abc.txt"); But it is always returning a null. I need to read from that file, and I read that if you put the files in WEB-INF, you can access them with getResourceAsStream, yet the method is always returning a null. Any ideas of what I may be doing wrong? Btw, the strange thing is that this was working, but after I performed a Clean and Build on the Project, it suddenly stopped working :/

    Read the article

  • What is the proper way to code a read-while loop in Scala?

    - by ARKBAN
    What is the "proper" of writing the standard read-while loop in Scala? By proper I mean written in a Scala-like way as opposed to a Java-like way. Here is the code I have in Java: MessageDigest md = MessageDigest.getInstance( "MD5" ); InputStream input = new FileInputStream( "file" ); byte[] buffer = new byte[1024]; int readLen; while( ( readLen = input.read( buffer ) ) != -1 ) md.update( buffer, 0, readLen ); return md.digest(); Here is the code I have in Scala: val md = MessageDigest.getInstance( hashInfo.algorithm ) val input = new FileInputStream( "file" ) val buffer = new Array[ Byte ]( 1024 ) var readLen = 0 while( readLen != -1 ) { readLen = input.read( buffer ) if( readLen != -1 ) md.update( buffer, 0, readLen ) } md.digest The Scala code is correct and works, but feels very un-Scala-ish. For one it is a literal translation of the Java code, taking advantage of none of the advantages of Scala. Further it is actually longer than the Java code! I really feel like I'm missing something, but I can't figure out what. I'm fairly new to Scala, and so I'm asking the question to avoid falling into the pitfall of writing Java-style code in Scala. I'm more interested in the Scala way to solve this kind of problem than in any specific helper method that might be provided by the Scala API to hash a file. (I apologize in advance for my ad hoc Scala adjectives throughout this question.)

    Read the article

  • Filling in uninitialized array in java? (or workaround!)

    - by AlexRamallo
    Hello all, I'm currently in the process of creating an OBJ importer for an opengles android game. I'm relatively new to the language java, so I'm not exactly clear on a few things. I have an array which will hold the number of vertices in the model(along with a few other arrays as well): float vertices[]; The problem is that I don't know how many vertices there are in the model before I read the file using the inputstream given to me. Would I be able to fill it in as I need to like this?: vertices[95] = 5.004f; //vertices was defined like the example above or do I have to initialize it beforehand? if the latter is the case then what would be a good way to find out the number of vertices in the file? Once I read it using inputstreamreader.read() it goes to the next line until it reads the whole file. The only thing I can think of would be to read the whole file, count the number of vertices, then read it AGAIN the fill in the newly initialized array. Is there a way to dynamically allocate the data as is needed?

    Read the article

  • J2ME/Java: Referencing StringBuffer through Threads

    - by Jemuel Dalino
    This question might be long, but I want to provide much information. Overview: I'm creating a Stock Quotes Ticker app for Blackberry. But I'm having problems with my StringBuffer that contains an individual Stock information. Process: My app connects to our server via SocketConnection. The server sends out a formatted set of strings that contains the latest Stock trade. So whenever a new trade happens, the server will send out an individual Stock Quote of that trade. Through an InputStream I am able to read that information and place each character in a StringBuffer that is referenced by Threads. By parsing based on char3 I am able to determine a set of stock quote/information. char1 - to separate data char3 - means end of a stock quote/information sample stock quote format sent out by our server: stock_quote_name(char 1)some_data(char1)some_data(char1)(char3) My app then parses that stock quote to compare certain data and formats it how it will look like when displayed in the screen. When trades happen gradually(slow) the app works perfectly. However.. Problem: When trades happen too quickly and almost at the same time, My app is not able to handle the information sent efficiently. The StringBuffer has its contents combined with the next trade. Meaning Two stock information in one StringBuffer. field should be: Stock_quote_name some_data some_data sample of what's happening: Stock_quote_name some_data some_dataStock_quote_name some_data some_data here's my code for this part: while (-1 != (data = is.read())) { sb.append((char)data); while(3 != (data = is.read())) { sb.append((char)data); } UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { try { synchronized(UiApplication.getEventLock()) { SetStringBuffer(sb); DisplayStringBuffer(); RefreshStringBuffer(); } } catch (Exception e) { System.out.println("Error in setting stringbuffer: " + e.toString()); } } }); } public synchronized void DisplayStringBuffer() { try { //parse sb - string buffer ...... } catch(Exception ex) { System.out.println("error in DisplayStringBuffer(): " + ex.toString()); } } public synchronized void SetStringBuffer(StringBuffer dataBuffer) { this.sb =dataBuffer; System.out.println(sb); } public synchronized void RefreshStringBuffer() { this.sb.delete(0, this.sb.length()); } From what I can see, when trades happen very fast, The StringBuffer is not refreshed immediately and still has the contents of the previous trade, when i try to put new data. My Question is: Do you guys have any suggestion on how i can put data into the StringBuffer, without the next information being appended to the first content

    Read the article

  • Raw XML Push from input stream captures only the first line of XML

    - by pqsk
    I'm trying to read XML that is being pushed to my java app. I originally had this in my glassfish server working. The working code in glassfish is as follows: public class XMLPush implements Serializable { public void processXML() { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getReader (); String s = null; while((s = br.readLine ()) != null) { sb.append ( s ); } //other code to process xml ........... ............................. }catch(Exception ex) { XMLCreator.exceptionOutput ( "processXML","Exception",ex); } .... ..... }//processXML }//class It works perfect, but my client is unable to have glassfish on their server. I tried grabbing the raw xml from php, but I couldn't get it to work. I decided to open up a socket and listen for the xml push manually. Here is my code for receiving the push: public class ListenerService extends Thread { private BufferedReader reader = null; private String line; public ListenerService ( Socket connection )thows Exception { this.reader = new BufferedReader ( new InputStreamReader ( connection.getInputStream () ) ); this.line = null; }//ListenerService @Override public void run () { try { while ( (this.line = this.reader.readLine ()) != null) { System.out.println ( this.line ); ........ }//while } System.out.println ( ex.toString () ); } } catch ( Exception ex ) { ... }//catch }//run I haven't done much socket programing, but from what I read for the past week is that passing the xml into a string is bad. What am I doing wrong and why is it that in glassfish server it works, and when I just open a socket myself it doesn't? this is all that I receive from the push: PUT /?XML_EXPORT_REASON=ResponseLoop&TIMESTAMP=1292559547 HTTP/1.1 Host: ************************ Accept: */* Content-Length: 470346 Expect: 100-continue <?xml version="1.0" encoding="UTF-8" ?> Where did the xml go? Is it because I am placing it in a string? I just need to grab the xml and save it into a file and then process it. Everything else works, but this.Any help would be greatly appreciated.

    Read the article

  • Creating a byte array from a stream

    - by Bob
    What is the preffered method for creating a byte array from an input stream? Here is my current solution with .NET 3.5. Is it still a better idea to read and write chunks of the stream? Stream s; byte[] b; using (BinaryReader br = new BinaryReader(s)) { b = br.ReadBytes(s.Length); }

    Read the article

  • getting incorrect error even if the condition is fulfilled

    - by Tapan Desai
    I am trying to show the message based on the text shown on webpage after a particular action. If the webpage contains text MESSAGE HAS BEEN SUBMITTED SUCCESSFULLY, I want to print Message sent successfully on the screen otherwise MESSAGE SENDING FAILED. Everything is working fine but for one thing. PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(sendConnection.getOutputStream()), true); printWriter.print(sendContent); printWriter.flush(); printWriter.close(); //Reading the returned web page to analyse whether the operation was sucessfull BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sendConnection.getInputStream())); StringBuilder SendResult = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { SendResult.append(line); } if (SendResult.toString().contains("MESSAGE HAS BEEN SUBMITTED SUCCESSFULLY")) { System.out.println("Message sent to " + phoneNumber + " successfully."); } else { System.err.println("Message could not send to " + phoneNumber + ". Also check login credentials"); } bufferedReader.close(); The problem is that even if the webpage contains the text MESSAGE HAS BEEN SUBMITTED SUCCESSFULLY, the condition always goes into ELSE part and show MESSAGE SENDING FAILED but thats not true because the message has been sent and i see the MESSAGE HAS BEEN SUBMITTED SUCCESSFULLY on the webpage. Can anyone tell me where am i going wrong?

    Read the article

  • Access to Perl's empty angle "<>" operator from an actual filehandle?

    - by Ryan Thompson
    I like to use the nifty perl feature where reading from the empty angle operator <> magically gives your program UNIX filter semantics, but I'd like to be able to access this feature through an actual filehandle (or IO::Handle object, or similar), so that I can do things like pass it into subroutines and such. Is there any way to do this? This question is particularly hard to google, because searching for "angle operator" and "filehandle" just tells me how to read from filehandles using the angle operator.

    Read the article

  • Huge file in Clojure and Java heap space error

    - by trzewiczek
    I posted before on a huge XML file - it's a 287GB XML with Wikipedia dump I want ot put into CSV file (revisions authors and timestamps). I managed to do that till some point. Before I got the StackOverflow Error, but now after solving the first problem I get: java.lang.OutOfMemoryError: Java heap space error. My code (partly taken from Justin Kramer answer) looks like that: (defn process-pages [page] (let [title (article-title page) revisions (filter #(= :revision (:tag %)) (:content page))] (for [revision revisions] (let [user (revision-user revision) time (revision-timestamp revision)] (spit "files/data.csv" (str "\"" time "\";\"" user "\";\"" title "\"\n" ) :append true))))) (defn open-file [file-name] (let [rdr (BufferedReader. (FileReader. file-name))] (->> (:content (data.xml/parse rdr :coalescing false)) (filter #(= :page (:tag %))) (map process-pages)))) I don't show article-title, revision-user and revision-title functions, because they just simply take data from a specific place in the page or revision hash. Anyone could help me with this - I'm really new in Clojure and don't get the problem.

    Read the article

  • Is there a concise way to create an InputSupplier for an InputStream in Google Guava?

    - by Fabian Steeg
    There are a few factory methods in Google Guava to create InputSuppliers, e.g. from a byte[]: ByteStreams.newInputStreamSupplier(bytes); Or from a File: Files.newInputStreamSupplier(file); Is there a similar way to to create an InputSupplier for a given InputStream? That is, a way that's more concise than an anonymous class: new InputSupplier<InputStream>() { public InputStream getInput() throws IOException { return inputStream; } }; Background: I'd like to use InputStreams with e.g. Files.copy(...) or ByteStreams.equal(...).

    Read the article

  • How can I determine if a file I want to read from actually exists?

    - by Imray
    I'm learning Java, and I'm trying to write a program that can read from a .ser file, which I've already created with a writeTo method. I want to know a given file exists in the system before I tell the program to read from it. My code looks like this: public boolean readFromSerializedFile(String fileName){ FileInputStream fileInStream = null; ObjectInputStream objectInStream = null; try{ fileInStream = new FileInputStream(fileName); objectInStream = new ObjectInputStream(fileInStream); Is there a simple way I can determine if the file with the name of the parameter exists in the root directory (or wherever else specified)?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >