Search Results

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

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

  • implementing keepalives with Java

    - by Bilal
    Hi All, I am biulding a client-server application where I have to implement a keepalive mechanism in order to detect that the client has crashed or not. I have separate threads on both client and server side. the client thread sends a "ping" then sleeps for 3 seconds, while the server reads the BufferedInput Stream and checks whether ping is received, if so it makes the ping counter eqauls zero, else it increments the counter by +1, the server thread then sleeps for 3 seconds, if the ping counter reaches 3, it daclares the client as dead. The problem is that when the server reads the input stream, its a blocking call, and it blocks untill the next ping is received, irrespective of how delayed it is, so the server never detects a missed ping. any suggestions, so that I can read the current value of the stream and it doesn't block if there is nothing on the incoming stream. Thanks,

    Read the article

  • StringBufferInputStream Question in Java

    - by JJG
    I want to read an input string and return it as a UTF8 encoded string. SO I found an example on the Oracle/Sun website that used FileInputStream. I didn't want to read a file, but a string, so I changed it to StringBufferInputStream and used the code below. The method parameter jtext, is some Japanese text. Actually this method works great. The question is about the deprecated code. I had to put @SuppressWarnings because StringBufferInputStream is deprecated. I want to know is there a better way to get a string input stream? Is it ok just to leave it as is? I've spent so long trying to fix this problem that I don't want to change anything now I seem to have cracked it. @SuppressWarnings("deprecation") private String readInput(String jtext) { StringBuffer buffer = new StringBuffer(); try { StringBufferInputStream sbis = new StringBufferInputStream (jtext); InputStreamReader isr = new InputStreamReader(sbis, "UTF8"); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char)ch); } in.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); return null; } }

    Read the article

  • How can I get size in bytes of an object sent using RMI?

    - by Lucas Batistussi
    I'm implementing a cache server with MongoDB and ConcurrentHashMap java class. When there are available space to put object in memory, it will put at. Otherwise, the object will be saved in a mongodb database. Is allowed that user specify a size limit in memory (this should not exceed heap size limit obviously!) for the memory cache. The clients can use the cache service connecting through RMI. I need to know the size of each object to verify if a new incoming object can be put into memory. I searched over internet and i got this solution to get size: public long getObjectSize(Object o){ try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(o); oos.close(); return bos.size(); } catch (Exception e) { return Long.MAX_VALUE; } } This solution works very well. But, in terms of memory use doesn't solve my problem. :( If many clients are verifying the object size at same time this will cause stack overflow, right? Well... some people can say: Why you don't get the specific object size and store it in memory and when another object is need to put in memory check the object size? This is not possible because the objects are variable in size. :( Someone can help me? I was thinking in get socket from RMI communication, but I don't know how to do this...

    Read the article

  • How to store multiple variables from a File Input of unknown size in Java?

    - by AlphaOmegaStrife
    I'm a total beginner with my first programming assignment in Java. For our programming assignment, we will be given a .txt file of students like so: 3 345 Lisa Miller 890238 Y 2 <-(Number of classes) Mathematics MTH345 4 A Physics PHY357 3 B Bill Wilton 798324 N 2 English ENG378 3 B Philosophy PHL534 3 A Dandy Goat 746333 Y 1 History HIS101 3 A" The teacher will give us a .txt file on the day of turning it in with a list of unknown students. My problem is: I have a specific class for turning the data from the file into variables to be used for a different class in printing it to the screen. However, I do not know of a good way to get the variables from the input file for the course numbers, since that number is not predetermined. The only way I can think of to iterate over that unknown amount is using a loop, but that would just overwrite my variables every time. Also, the teacher has requested that we not use any JCL classes (I don't really know what this means.) Sorry if I have done a poor job of explaining this, but I can't think of a better way to conceptualize it. Let me know if I can clarify. Edit: public static void analyzeData() { Scanner inputStream = null; try { inputStream = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt")); } catch (FileNotFoundException e) { System.out.println("File Programming Assignment 1 Data.txt could not be found or opened."); System.exit(0); } int numberOfStudents = inputStream.nextInt(); int tuitionPerHour = inputStream.nextInt(); String firstName = inputStream.next(); String lastname = inputStream.next(); String isTuitionPaid = inputStream.next(); int numberOfCourses = inputStream.nextInt(); String courseName = inputStream.next(); String courseNumber = inputStream.next(); int creditHours = inputStream.nextInt(); String grade = inputStream.next(); To show the methods I am using now, I am just using a Scanner to read from the file and for Scanner inputStream, I am using nextInt() or next() to get variables from the file. Obviously this will not work when I do not know exactly how many classes each student will have.

    Read the article

  • FindBugs: "may fail to close stream" - is this valid in case of InputStream?

    - by thSoft
    In my Java code, I start a new process, then obtain its input stream to read it: BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); FindBugs reports an error here: may fail to close stream Pattern id: OS_OPEN_STREAM, type: OS, category: BAD_PRACTICE Must I close the InputStream of another process? And what's more, according to its Javadoc, InputStream#close() does nothing. So is this a false positive, or should I really close the input stream of the process when I'm done?

    Read the article

  • Android - getting from a Uri to an InputStream to a byte array?

    - by AP257
    Hi there I'm trying to get from an Android Uri to a byte array. I have the following code, but it keeps telling me that the byte array is 61 bytes long, even though the file is quite large - so I think it may be turning the Uri string into a byte array, rather than the file :( Log.d(LOG_TAG, "fileUriString = " + fileUriString); Uri tempuri = Uri.parse(fileUriString); InputStream is = cR.openInputStream(tempuri); String str=is.toString(); byte[] b3=str.getBytes(); Log.d(LOG_TAG, "len of data is " + imageByteArray.length + " bytes"); Please can someone help me work out what to do? The output is "fileUriString = content://media/external/video/media/53" and "len of data is 61 bytes". Thanks!

    Read the article

  • Can you decode a mutable Bitmap from an InputStream?

    - by Daniel Lew
    Right now I've got an Android application that: Downloads an image. Does some pre-processing to that image. Displays the image. The dilemma is that I would like this process to use less memory, so that I can afford to download a higher-resolution image. However, when I download the image now, I use BitmapFactory.decodeStream(), which has the unfortunate side effect of returning an immutable Bitmap. As a result, I'm having to create a copy of the Bitmap before I can start operating on it, which means I have to have 2x the size of the Bitmap's memory allocated (at least for a brief period of time; once the copy is complete I can recycle the original). Is there a way to decode an InputStream into a mutable Bitmap?

    Read the article

  • Why does my Sax Parser produce no results after using InputStream Read?

    - by Andy Barlow
    Hello, I have this piece of code which I'm hoping will be able to tell me how much data I have downloaded (and soon put it in a progress bar), and then parse the results through my Sax Parser. If I comment out basically everything above the //xr.parse(new InputSource(request.getInputStream())); line and swap the xr.parse's over, it works fine. But at the moment, my Sax parser tells me I have nothing. Is it something to do with is.read (buffer) section? Also, just as a note, request is a HttpURLConnection with various signatures. /*Input stream to read from our connection*/ InputStream is = request.getInputStream(); /*we make a 2 Kb buffer to accelerate the download, instead of reading the file a byte at once*/ byte [ ] buffer = new byte [ 2048 ] ; /*How many bytes do we have already downloaded*/ int totBytes,bytes,sumBytes = 0; totBytes = request.getContentLength () ; while ( true ) { /*How many bytes we got*/ bytes = is.read (buffer); /*If no more byte, we're done with the download*/ if ( bytes <= 0 ) break; sumBytes+= bytes; Log.v("XML", sumBytes + " of " + totBytes + " " + ( ( float ) sumBytes/ ( float ) totBytes ) *100 + "% done" ); } /* Parse the xml-data from our URL. */ // OLD, and works if comment all the above //xr.parse(new InputSource(request.getInputStream())); xr.parse(new InputSource(is)) /* Parsing has finished. */; Can anyone help me at all?? Kind regards, Andy

    Read the article

  • Why do my Sax Parser produce no results after using InputStream Read?

    - by Andy Barlow
    Hello, I have this piece of code which I'm hoping will be able to tell me how much data I have downloaded (and soon put it in a progress bar), and then parse the results through my Sax Parser. If I comment out basically everything above the //xr.parse(new InputSource(request.getInputStream())); line and swap the xr.parse's over, it works fine. But at the moment, my Sax parser tells me I have nothing. Is it something to do with is.read (buffer) section? Also, just as a note, request is a HttpURLConnection with various signatures. /*Input stream to read from our connection*/ InputStream is = request.getInputStream(); /*we make a 2 Kb buffer to accelerate the download, instead of reading the file a byte at once*/ byte [ ] buffer = new byte [ 2048 ] ; /*How many bytes do we have already downloaded*/ int totBytes,bytes,sumBytes = 0; totBytes = request.getContentLength () ; while ( true ) { /*How many bytes we got*/ bytes = is.read (buffer); /*If no more byte, we're done with the download*/ if ( bytes <= 0 ) break; sumBytes+= bytes; Log.v("XML", sumBytes + " of " + totBytes + " " + ( ( float ) sumBytes/ ( float ) totBytes ) *100 + "% done" ); } /* Parse the xml-data from our URL. */ // OLD, and works if comment all the above //xr.parse(new InputSource(request.getInputStream())); xr.parse(new InputSource(is)) /* Parsing has finished. */; Can anyone help me at all?? Kind regards, Andy

    Read the article

  • How to use log4j for a axis2 webservice

    - by KItis
    I have created a simple axis2 webservice to understand logging functionality in a webservice. in this sample webservice, when a client calls this webservice, first it reads the log4j.property file. then i can see the logs being printed on console. but i have included file appender too into the property file. but i can not file the log file any where in my sample webapplication. i am using tomcat to run the webservice. following is webservice interface method called by client. package test; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class WSInterface { static final Logger logger = Logger.getLogger(WSInterface.class); public String log4jTest(String input){ InputStream inputStream = this.getClass().getClassLoader() .getResourceAsStream(input); Properties properties = new Properties(); System.out.println("InputStream is: " + inputStream); //load the inputStream using the Properties try { properties.load(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } PropertyConfigurator.configure(properties); logger.debug("Hello World!"); Class myclass = WSInterface.class; String url = myclass.getResource("WSInterface.class").toString(); String output = ""; return url; } }

    Read the article

  • Can I set a timeout for a InputStream's read() function?

    - by Zombies
    I have a DataInputStream that I obtained from a Socket. Is there any way I can set a timeout for dis.read(...)? Currently I spawn a new thread to do the read. While the parent thread does a thread.join(timeout) to wait before interrupting it. I am aware of nio, but I don't think I want to refactor that much at this point. Thanks.

    Read the article

  • xstream handles non-english character

    - by Yan Cheng CHEOK
    I have the following code : /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package helloworld; import com.thoughtworks.xstream.XStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JOptionPane; /** * * @author yccheok */ public class Test { @SuppressWarnings("unchecked") public static <A> A fromXML(Class c, File file) { XStream xStream = new XStream(); InputStream inputStream = null; try { inputStream = new java.io.FileInputStream(file); Object object = xStream.fromXML(inputStream); if (c.isInstance(object)) { return (A)object; } } catch (Exception exp) { exp.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); inputStream = null; } catch (java.io.IOException exp) { exp.printStackTrace(); return null; } } } return null; } @SuppressWarnings("unchecked") public static <A> A fromXML(Class c, String filePath) { return (A)fromXML(c, new File(filePath)); } public static boolean toXML(Object object, File file) { XStream xStream = new XStream(); OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); xStream.toXML(object, outputStream); } catch (Exception exp) { exp.printStackTrace(); return false; } finally { if (outputStream != null) { try { outputStream.close(); outputStream = null; } catch (java.io.IOException exp) { exp.printStackTrace(); return false; } } } return true; } public static boolean toXML(Object object, String filePath) { return toXML(object, new File(filePath)); } public static void main(String args[]) { String s = "\u6210\u4EA4\u91CF"; // print ??? System.out.println(s); // fine! show ??? JOptionPane.showMessageDialog(null, s); toXML(s, "C:\\A.XML"); String o = fromXML(String.class, "C:\\A.XML"); // show ??? JOptionPane.showMessageDialog(null, o); } } I run the following code through command prompt in Windows Vista. 1) May I know why System.out.println unable to print out Chinese Character in console? 2) I open up the xstream file. The saved value is <string>???</string> How can I make xstream save Chinese Character correctly? Thanks.

    Read the article

  • I'm getting this exception : Unresolved compilation problems

    - by Stephan
    I get this exception after i removed from my project the jars (pdfbox ,bouncycastle etc) and moved them to another folder but i included them in the build path ... at the first line eclipse shows this error( the constructor PDFParser(InputStream) refers to missing type InputStream) -altought FileInputStream is extended from InputStream- and i don't know why? FileInputStream in = new FileInputStream(path); PDFParser parser = new PDFParser(in); PDFTextStripper textStripper = new PDFTextStripper(); parser.parse(); String text = textStripper.getText(new PDDocument(parser.getDocument())); any ideas? ** Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems: The constructor PDFParser(InputStream) refers to the missing type InputStream The constructor PDFTextStripper() refers to the missing type IOException The method parse() from the type PDFParser refers to the missing type IOException The method getText(PDDocument) from the type PDFTextStripper refers to the missing type IOException The method getDocument() from the type PDFParser refers to the missing type IOException The method getDocument() from the type PDFParser refers to the missing type IOException The method close() from the type COSDocument refers to the missing type IOException **

    Read the article

  • Handling file upload in a non-blocking manner

    - by Kaliyug Antagonist
    The background thread is here Just to make objective clear - the user will upload a large file and must be redirected immediately to another page for proceeding different operations. But the file being large, will take time to be read from the controller's InputStream. So I unwillingly decided to fork a new Thread to handle this I/O. The code is as follows : The controller servlet /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("In Controller.doPost(...)"); TempModel tempModel = new TempModel(); tempModel.uploadSegYFile(request, response); System.out.println("Forwarding to Accepted.jsp"); /*try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ request.getRequestDispatcher("/jsp/Accepted.jsp").forward(request, response); } The model class package com.model; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.utils.ProcessUtils; public class TempModel { public void uploadSegYFile(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub System.out.println("In TempModel.uploadSegYFile(...)"); /* * Trigger the upload/processing code in a thread, return immediately * and notify when the thread completes */ try { FileUploaderRunnable fileUploadRunnable = new FileUploaderRunnable( request.getInputStream()); /* * Future<FileUploaderRunnable> future = ProcessUtils.submitTask( * fileUploadRunnable, fileUploadRunnable); * * FileUploaderRunnable processed = future.get(); * * System.out.println("Is file uploaded : " + * processed.isFileUploaded()); */ Thread uploadThread = new Thread(fileUploadRunnable); uploadThread.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * catch (InterruptedException e) { // TODO Auto-generated catch block * e.printStackTrace(); } catch (ExecutionException e) { // TODO * Auto-generated catch block e.printStackTrace(); } */ System.out.println("Returning from TempModel.uploadSegYFile(...)"); } } The Runnable package com.model; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class FileUploaderRunnable implements Runnable { private boolean isFileUploaded = false; private InputStream inputStream = null; public FileUploaderRunnable(InputStream inputStream) { // TODO Auto-generated constructor stub this.inputStream = inputStream; } public void run() { // TODO Auto-generated method stub /* Read from InputStream. If success, set isFileUploaded = true */ System.out.println("Starting upload in a thread"); File outputFile = new File("D:/06c01_output.seg");/* * This will be changed * later */ FileOutputStream fos; ReadableByteChannel readable = Channels.newChannel(inputStream); ByteBuffer buffer = ByteBuffer.allocate(1000000); try { fos = new FileOutputStream(outputFile); while (readable.read(buffer) != -1) { fos.write(buffer.array()); buffer.clear(); } fos.flush(); fos.close(); readable.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("File upload thread completed"); } public boolean isFileUploaded() { return isFileUploaded; } } My queries/doubts : Spawning threads manually from the Servlet makes sense to me logically but scares me coding wise - the container isn't aware of these threads after all(I think so!) The current code is giving an Exception which is quite obvious - the stream is inaccessible as the doPost(...) method returns before the run() method completes : In Controller.doPost(...) In TempModel.uploadSegYFile(...) Returning from TempModel.uploadSegYFile(...) Forwarding to Accepted.jsp Starting upload in a thread Exception in thread "Thread-4" java.lang.NullPointerException at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:512) at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:497) at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:559) at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:324) at org.apache.coyote.Request.doRead(Request.java:422) at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:287) at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:407) at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:310) at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:202) at java.nio.channels.Channels$ReadableByteChannelImpl.read(Unknown Source) at com.model.FileUploaderRunnable.run(FileUploaderRunnable.java:39) at java.lang.Thread.run(Unknown Source) Keeping in mind the point 1., does the use of Executor framework help me in anyway ? package com.utils; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; public final class ProcessUtils { /* Ensure that no more than 2 uploads,processing req. are allowed */ private static final ScheduledThreadPoolExecutor threadPoolExec = new ScheduledThreadPoolExecutor( 2); public static <T> Future<T> submitTask(Runnable task, T result) { return threadPoolExec.submit(task, result); } } So how should I ensure that the user doesn't block and the stream remains accessible so that the (uploaded)file can be read from it?

    Read the article

  • sending sms to mobile from pc using java [closed]

    - by sjohnfernandas
    hi i need to send sms from pc to mobile phone can u people guide me to achieve? i used the following code to send sms to a mobile from pc but i did not get any output and also not getting any error so guide me and point out the mistakes what i have done. package mobilesms; import java.io.; import java.util.; import javax.comm.*; import java.io.IOException; import java.util.Properties; import java.io.InputStream; import java.io.OutputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; public class ReadSimple implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; OutputStream outputstream; InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) { portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals("COM1")) { System.out.println("Found port:COM1 "); ReadSimple reader = new ReadSimple(); } } } } public ReadSimple() { try { serialPort = (SerialPort) portId.open("ReadSimpleApp",500); } catch (PortInUseException e) { System.out.println(e); } try { inputStream = serialPort.getInputStream(); OutputStream out=serialPort.getOutputStream(); String line=""; line="AT"+"r\n"; out.write(line.trim().getBytes()); line=""; line="AT+CMGS=7639808583"+"\r\n"; out.write(line.trim().getBytes()); System.out.print(line); line="helloworld"; //line=”ATD 996544325;”+”\r\n”; out.write(line.trim().getBytes()); } catch (IOException e) { serialPort.close(); System.out.println(e); } // catch(InterruptedException E){E.printStackTrace();} try { serialPort.addEventListener(this); } catch (TooManyListenersException e) {System.out.println(e);} serialPort.notifyondataavailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {System.out.println(e);} readThread = new Thread(this); readThread.start(); } public void run() { try { Thread.sleep(200); } catch (InterruptedException e) {System.out.println(e);} } public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: byte[] readBuffer = new byte[10]; try { while (inputStream.available() 0) { int numBytes = inputStream.read(readBuffer); } System.out.println(new String(readBuffer)); } catch (IOException e) {System.out.println(e);} break; } } }

    Read the article

  • [SOLVED] BitmapFactory.decodeStream returning null when options are set.

    - by Robert Foss
    Hi! I'm having issues with BitmapFactory.decodeStream(inputStream). When using it without options, it will return an image. But when I use it with options as in .decodeStream(inputStream, null, options) it never returns Bitmaps. What I'm trying to do is to downsample a Bitmap before I actually load it to save memory. I've read some good guides, but none using .decodeStream. Here httpIM:NOT//nornalbion.SPAMcom/blog/?p=143 httpIM:NOT//kfb-android.blogspot.SPAMcom/2009/04/image-processing-in-android.html WORKS JUST FINE URL url = new URL(sUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); DOESNT WORK InputStream is = connection.getInputStream(); Bitmap img = BitmapFactory.decodeStream(is, null, options); InputStream is = connection.getInputStream(); Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math.abs(options.outWidth - TARGET_WIDTH); if(options.outHeight * options.outWidth * 2 >= 200*100*2){ // Load, scaling to smallest power of 2 that'll get it <= desired dimensions double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT : options.outWidth / TARGET_WIDTH; options.inSampleSize = (int)Math.pow(2d, Math.floor( Math.log(sampleSize)/Math.log(2d))); } // Do the actual decoding options.inJustDecodeBounds = false; Bitmap img = BitmapFactory.decodeStream(is, null, options);

    Read the article

  • ListField with image In Blackberry JDE

    - by Karthick
    I use the following code to retrieve image from the phone or SDCard and I use that image in to my ListField. It gives the output but it takes very Long time to produce the screen. How to solve this problem ?? Can any one help me?? Thanks in advance!!! String text = fileholder.getFileName(); try{ String path="file:///"+fileholder.getPath()+text; //path=”file:///SDCard/BlackBerry/pictures/image.bmp” InputStream inputStream = null; //Get File Connection FileConnection fileConnection = (FileConnection) Connector.open(path); inputStream = fileConnection.openInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int j = 0; while((j=inputStream.read()) != -1) { baos.write(j); } byte data[] = baos.toByteArray(); inputStream.close(); fileConnection.close(); //Encode and Resize image EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length); int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(180)); int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(180)); eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY); Bitmap bitmapImage = eImage.getBitmap(); graphics.drawBitmap(0, y+1, 40, 40,bitmapImage, 0, 0); graphics.drawText(text, 25, y,0,width); } catch(Exception e){}

    Read the article

  • Using ServletOutputStream to write very large files in a Java servlet without memory issues

    - by Martin
    I am using IBM Websphere Application Server v6 and Java 1.4 and am trying to write large CSV files to the ServletOutputStream for a user to download. Files are ranging from a 50-750MB at the moment. The smaller files aren't causing too much of a problem but with the larger files it appears that it is being written into the heap which is then causing an OutOfMemory error and bringing down the entire server. These files can only be served out to authenticated users over https which is why I am serving them through a Servlet instead of just sticking them in Apache. The code I am using is (some fluff removed around this): resp.setHeader("Content-length", "" + fileLength); resp.setContentType("application/vnd.ms-excel"); resp.setHeader("Content-Disposition","attachment; filename=\"export.csv\""); FileInputStream inputStream = null; try { inputStream = new FileInputStream(path); byte[] buffer = new byte[1024]; int bytesRead = 0; do { bytesRead = inputStream.read(buffer, offset, buffer.length); resp.getOutputStream().write(buffer, 0, bytesRead); } while (bytesRead == buffer.length); resp.getOutputStream().flush(); } finally { if(inputStream != null) inputStream.close(); } The FileInputStream doesn't seem to be causing a problem as if I write to another file or just remove the write completly the memory usage doesn't appear to be a problem. What I am thinking is that the resp.getOutputStream().write is being stored in memory until the data can be sent through to the client. So the entire file might be read and stored in the resp.getOutputStream() causing my memory issues and crashing! I have tried Buffering these streams and also tried using Channels from java.nio, none of which seems to make any bit of difference to my memory issues. I have also flushed the outputstream once per iteration of the loop and after the loop, which didn't help.

    Read the article

  • NSStream on Background didn't call

    - by Iphone Developer
    - (void)applicationDidEnterBackground:(UIApplication *)application { NSOutputStream *outputStream; NSInputStream *inputStream; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [inputStream setDelegate:self]; [outputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }); } Input,OutputStream delegate didn't call.What i am doing wrong.

    Read the article

  • Image rescale and write rescaled image file in blackberry

    - by Karthick
    I am using the following code to resize and save the file in to the blackberry device. After image scale I try to write image file into device. But it gives the same data. (Height and width of the image are same).I have to make rescaled image file.Can anyone help me ??? class ResizeImage extends MainScreen implements FieldChangeListener { private String path="file:///SDCard/BlackBerry/pictures/test.jpg"; private ButtonField btn; ResizeImage() { btn=new ButtonField("Write File"); btn.setChangeListener(this); add(btn); } public void fieldChanged(Field field, int context) { if (field == btn) { try { InputStream inputStream = null; //Get File Connection FileConnection fileConnection = (FileConnection) Connector.open(path); if (fileConnection.exists()) { inputStream = fileConnection.openInputStream(); //byte data[]=inputStream.toString().getBytes(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int j = 0; while((j=inputStream.read()) != -1) { baos.write(j); } byte data[] = baos.toByteArray(); inputStream.close(); fileConnection.close(); WriteFile("file:///SDCard/BlackBerry/pictures/org_Image.jpg",data); EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length); int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(80)); int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(80)); eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY); WriteFile("file:///SDCard/BlackBerry/pictures/resize.jpg",eImage.getData()); BitmapField bit=new BitmapField(eImage.getBitmap()); add(bit); } } catch(Exception e) { System.out.println("Exception is ==> "+e.getMessage()); } } } void WriteFile(String fileName,byte[] data) { FileConnection fconn = null; try { fconn = (FileConnection) Connector.open(fileName,Connector.READ_WRITE); } catch (IOException e) { System.out.print("Error opening file"); } if (fconn.exists()) try { fconn.delete(); } catch (IOException e) { System.out.print("Error deleting file"); } try { fconn.create(); } catch (IOException e) { System.out.print("Error creating file"); } OutputStream out = null; try { out = fconn.openOutputStream(); } catch (IOException e) { System.out.print("Error opening output stream"); } try { out.write(data); } catch (IOException e) { System.out.print("Error writing to output stream"); } try { fconn.close(); } catch (IOException e) { System.out.print("Error closing file"); } } }

    Read the article

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