Search Results

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

Page 9/23 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • design for a wrapper around command-line utilities

    - by hatchetman82
    im trying to come up with a design for a wrapper for use when invoking command line utilities in java. the trouble with runtime.exec() is that you need to keep reading from the process' out and err streams or it hangs when it fills its buffers. this has led me to the following design: public class CommandLineInterface { private final Thread stdOutThread; private final Thread stdErrThread; private final OutputStreamWriter stdin; private final History history; public CommandLineInterface(String command) throws IOException { this.history = new History(); this.history.addEntry(new HistoryEntry(EntryTypeEnum.INPUT, command)); Process process = Runtime.getRuntime().exec(command); stdin = new OutputStreamWriter(process.getOutputStream()); stdOutThread = new Thread(new Leech(process.getInputStream(), history, EntryTypeEnum.OUTPUT)); stdOutThread.setDaemon(true); stdOutThread.start(); stdErrThread = new Thread(new Leech(process.getErrorStream(), history, EntryTypeEnum.ERROR)); stdErrThread.setDaemon(true); stdErrThread.start(); } public void write(String input) throws IOException { this.history.addEntry(new HistoryEntry(EntryTypeEnum.INPUT, input)); stdin.write(input); stdin.write("\n"); stdin.flush(); } } public class Leech implements Runnable{ private final InputStream stream; private final History history; private final EntryTypeEnum type; private volatile boolean alive = true; public Leech(InputStream stream, History history, EntryTypeEnum type) { this.stream = stream; this.history = history; this.type = type; } public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; try { while(alive) { line = reader.readLine(); if (line==null) break; history.addEntry(new HistoryEntry(type, line)); } } catch (Exception e) { e.printStackTrace(); } } } my issue is with the Leech class (used to "leech" the process' out and err streams and feed them into history - which acts like a log file) - on the one hand reading whole lines is nice and easy (and what im currently doing), but it means i miss the last line (usually the prompt line). i only see the prompt line when executing the next command (because there's no line break until that point). on the other hand, if i read characters myself, how can i tell when the process is "done" ? (either complete or waiting for input) has anyone tried something like waiting 100 millis since the last output from the process and declaring it "done" ? any better ideas on how i can implement a nice wrapper around things like runtime.exec("cmd.exe") ?

    Read the article

  • NullPointerException, Collections not storing data?

    - by Elliott
    Hi there, I posted this question earlier but not with the code in its entirety. The coe below also calls to other classes Background and Hydro which I have included at the bottom. I have a Nullpointerexception at the line indicate by asterisks. Which would suggest to me that the Collections are not storing data properly. Although when I check their size they seem correct. Thanks in advance. PS: If anyone would like to give me advice on how best to format my code to make it readable, it would be appreciated. Elliott package exam0607; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Collection; import java.util.Scanner; import java.util.Vector; import exam0607.Hydro; import exam0607.Background;// this may not be necessary???? FIND OUT public class HydroAnalysis { public static void main(String[] args) { Collection hydroList = null; Collection backList = null; try{hydroList = readHydro("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_data.dat");} catch (IOException e){ e.getMessage();} try{backList = readBackground("http://www.hep.ucl.ac.uk/undergrad/3459/exam_data/2006-07/final/hd_bgd.dat"); //System.out.println(backList.size()); } catch (IOException e){ e.getMessage();} for(int i =0; i <=14; i++ ){ String nameroot = "HJK"; String middle = Integer.toString(i); String hydroName = nameroot + middle + "X"; System.out.println(hydroName); ALGO_1(hydroName, backList, hydroList); } } public static Collection readHydro(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Collection data = new Vector(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); System.out.println(name); double starttime = Double.parseDouble(s.next()); System.out.println(+starttime); double increment = Double.parseDouble(s.next()); System.out.println(+increment); double p = 0; double nterms = 0; while(s.hasNextDouble()){ p = Double.parseDouble(s.next()); System.out.println(+p); nterms++; System.out.println(+nterms); } Hydro SAMP = new Hydro(name, starttime, increment, p); data.add(SAMP); } return data; } public static Collection readBackground(String url) throws IOException { URL u = new URL(url); InputStream is = u.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader b = new BufferedReader(isr); String line =""; Vector data = new Vector(); while((line = b.readLine())!= null){ Scanner s = new Scanner(line); String name = s.next(); //System.out.println(name); double starttime = Double.parseDouble(s.next()); //System.out.println(starttime); double increment = Double.parseDouble(s.next()); //System.out.println(increment); double sum = 0; double p = 0; double nterms = 0; while((s.hasNextDouble())){ p = Double.parseDouble(s.next()); //System.out.println(p); nterms++; sum += p; } double pbmean = sum/nterms; Background SAMP = new Background(name, starttime, increment, pbmean); //System.out.println(SAMP); data.add(SAMP); } return data; } public static void ALGO_1(String hydroName, Collection backgs, Collection hydros){ //double aMin = Double.POSITIVE_INFINITY; //double sum = 0; double intensity = 0; double numberPN_SIG = 0; double POSITIVE_PN_SIG =0; //int numberOfRays = 0; for(Hydro hd: hydros){ System.out.println(hd.H_NAME); for(Background back : backgs){ System.out.println(back.H_NAME); if(back.H_NAME.equals(hydroName)){//ERROR HERE double PN_SIG = Math.max(0.0, hd.PN - back.PBMEAN); numberPN_SIG ++; if(PN_SIG 0){ intensity += PN_SIG; POSITIVE_PN_SIG ++; } } } double positive_fraction = POSITIVE_PN_SIG/numberPN_SIG; if(positive_fraction < 0.5){ System.out.println( hydroName + "is faulty" ); } else{System.out.println(hydroName + "is not faulty");} System.out.println(hydroName + "has instensity" + intensity); } } } THE BACKGROUND CLASS package exam0607; public class Background { String H_NAME; double T_START; double DT; double PBMEAN; public Background(String name, double starttime, double increment, double pbmean) { name = H_NAME; starttime = T_START; increment = DT; pbmean = PBMEAN; }} AND THE HYDRO CLASS public class Hydro { String H_NAME; double T_START; double DT; double PN; public double n; public Hydro(String name, double starttime, double increment, double p) { name = H_NAME; starttime = T_START; increment = DT; p = PN; } }

    Read the article

  • Easy to get a test file into JUnit

    - by Benju
    Can somebody suggest an easy way to get a reference to a file as a String/InputStream/File/etc type object in a junit test class? Obviously I could paste the file (xml in this case) in as a giant String or read it in as a file but is there a shortcut specific to Junit like this? public class MyTestClass{ @Resource(path="something.xml") File myTestFile; @Test public void toSomeTest(){ ... } }

    Read the article

  • Handling downloads in Java

    - by Tereno
    Hi there, How would I be able to handle downloads using HttpResponse in Java? I made an HttpGet request to a specific site - the site returns the file to be downloaded. How can I handle this download? InputStream doesn't seem to be able to handle it (or maybe I'm using it the wrong way.)

    Read the article

  • How to read attachment messages without using scriptlets in JSP?

    - by Stardust
    Hi, I want to know how can I read attachment messages without using scriplets in JSP? After getting Message object as an attribute by using request object from servlets, how can I confirm whether Message content is an instance of Multipart or not without using scriplets like: if(message.getContent() instanceOf Multipart) How can I read the content of any file by using EL in JSP? As I can't see any getRead method in inputStream subclass.

    Read the article

  • Java NIO Servlet to File

    - by Gandalf
    Is there a way (without buffering the whole Inputstream) to take the HttpServletRequest from a Java Servlet and write it out to a file using all NIO? Is it even worth trying? Will it be any faster reading from a normal java.io stream and writing to a java.nio Channel or do they both really need to be pure NIO to see a benefit? Thanks.

    Read the article

  • Java: Detecting image format, resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • Eclipse getResourceAsStream returning null

    - by Chris
    I cannot get getResourceAsStream to find a file. I have put the file in the top level dir, target dir, etc, etc and have tried it with a "/" in front as well. Everytime it returns null. Any suggestions ? Thanks. public class T { public static final void main(String[] args) { InputStream propertiesIS = T.class.getClassLoader().getResourceAsStream("test.txt"); System.out.println("Break"); } }

    Read the article

  • Android - How to set the wallpaper image?

    - by asdf.BEN
    What i'm trying to do is, set the wallpaper using an image URI (no cropping) I'm a noob at dev on Android and dev in general. The internet has failed me... on providing code to set the wallpaper. yes the dev resource site says public void setStream (InputStream data) but i don't understand it, some sample code would greatly help me.

    Read the article

  • Problem with GwtUpload on GAE

    - by weesilmania
    I'm using GwtUpload to upload images on GAE. The problem is that the images seem to get much bigger when I move them into a blob. I've noticed the same for simple text fields and in that case I've realised that some weirdo characters are being appended to the end of the field values (encoding right?). Can anyone help? public class ImageUploadServlet extends AppEngineUploadAction { /** * Maintain a list with received files and their content types */ Hashtable<String, File> receivedFiles = new Hashtable<String, File>(); Hashtable<String, String> receivedContentTypes = new Hashtable<String, String>(); private Objectify objfy; public ImageUploadServlet() { ObjectifyService.register(Thumbnail.class); objfy = ObjectifyService.begin(); System.out.println("ImageUploadServlet init"); } /** * Override executeAction to save the received files in a custom place and * delete this items from session. */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { Thumbnail t = new Thumbnail(); for (FileItem item : sessionFiles) { //CacheableFileItem item = (CacheableFileItem)fItem; if (false == item.isFormField()) { System.out.println("the name 1st:" + item.getFieldName()); try { // You can also specify the temporary folder InputStream imgStream = item.getInputStream(); Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream)); t.setMainImage(imageBlob); System.out.println("blob: " + t.getMainImage()); } catch (Exception e) { throw new UploadActionException(e.getMessage()); } } else { System.out.println("the name 2nd:" + item.getFieldName()); String name = item.getFieldName(); String value; try { InputStream is = item.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer,"UTF-8"); value = writer.toString(); writer.close(); System.out.println("parm name: " + name); System.out.println("parm value: " + value + " **" + value.length()); System.out.println(item.getContentType()); if (name.equals("thumb-name")) { t.setName(value); } } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Error"); e.printStackTrace(); } } removeSessionFileItems(request); } objfy.put(t); return null; } As an example the size of the image is 20kb, and the lib has some debugging that confirms that this is the case when it's uploading the file but the blob ends up being over 1 MB. Wes

    Read the article

  • Loading jar file using JCL(JarClassLoader ) : classpath in manifest is ignored ..

    - by Xinus
    I am trying to load jar file using JCL using following code FileInputStream fis = new FileInputStream(new File( "C:\\Users\\sunils\\glassfish-tests\\working\\test.jar") ); JarClassLoader jc = new JarClassLoader( ); jc.add(fis); Class main = jc.loadClass( "highmark.test.Main" ); String[] str={}; main.getMethod("test").invoke(null);//.getDeclaredMethod("main",String[].class).invoke(null,str); fis.close(); But when I try to run this program I get Exception as Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at Main.main(Main.java:21) Caused by: java.lang.RuntimeException: Embedded startup not found, classpath is probably incomplete at org.glassfish.api.embedded.Server.<init>(Server.java:292) at org.glassfish.api.embedded.Server.<init>(Server.java:75) at org.glassfish.api.embedded.Server$Builder.build(Server.java:185) at org.glassfish.api.embedded.Server$Builder.build(Server.java:167) at highmark.test.Main.test(Main.java:33) ... 5 more According to this it is not able to locate class, But when I run the jar file explicitly it runs fine. It seems like JCL is ignoring other classes present in the jar file, MANIFEST.MF file in jar file shows: Manifest-Version: 1.0 Class-Path: . Main-Class: highmark.test.Main It seems to be ignoring Class-Path: . , This jar file runs fine when I run it using Java explicitly, This is just a test, in reality this jar file is coming as a InputStream and it cannot be stored in filesystem, How can I overcome this problem , Is there any workaround ? Thanks for any help . UNDATE: Here is a jar Main class : package highmark.test; import org.glassfish.api.embedded.*; import java.io.*; import org.glassfish.api.deployment.*; import com.sun.enterprise.universal.io.FileUtils; public class Main { public static void main(String[] args) throws IOException, LifecycleException, ClassNotFoundException { test(); } public static void test() throws IOException, LifecycleException, ClassNotFoundException{ Server.Builder builder = new Server.Builder("test"); Server server = builder.build(); server.createPort(8080); ContainerBuilder containerBuilder = server.createConfig(ContainerBuilder.Type.web); server.addContainer(containerBuilder); server.start(); File war=new File("C:\\Users\\sunils\\maventests\\simple-webapp\\target\\simple-webapp.war");//(File) inputStream.readObject(); EmbeddedDeployer deployer = server.getDeployer(); DeployCommandParameters params = new DeployCommandParameters(); params.contextroot = "simple"; deployer.deploy(war, params); } }

    Read the article

  • Java io ugly try-finally block

    - by Tom Brito
    Is there a not so ugly way of treat the close() exception to close both streams then: InputStream in = new FileInputStream(inputFileName); OutputStream out = new FileOutputStream(outputFileName); try { copy(in, out); } finally { try { in.close(); } catch (Exception e) { try { // event if in.close fails, need to close the out out.close(); } catch (Exception e2) {} throw e; // and throw the 'in' exception } out.close(); }

    Read the article

  • Performance of SHA-1 Checksum from Android 2.2 to 2.3 and Higher

    - by sbrichards
    In testing the performance of: package com.srichards.sha; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import com.srichards.sha.R; public class SHAHashActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = new TextView(this); String shaVal = this.getString(R.string.sha); long systimeBefore = System.currentTimeMillis(); String result = shaCheck(shaVal); long systimeResult = System.currentTimeMillis() - systimeBefore; tv.setText("\nRunTime: " + systimeResult + "\nHas been modified? | Hash Value: " + result); setContentView(tv); } public String shaCheck(String shaVal){ try{ String resultant = "null"; MessageDigest digest = MessageDigest.getInstance("SHA1"); ZipFile zf = null; try { zf = new ZipFile("/data/app/com.blah.android-1.apk"); // /data/app/com.blah.android-2.apk } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ZipEntry ze = zf.getEntry("classes.dex"); InputStream file = zf.getInputStream(ze); byte[] dataBytes = new byte[32768]; //65536 32768 int nread = 0; while ((nread = file.read(dataBytes)) != -1) { digest.update(dataBytes, 0, nread); } byte [] rbytes = digest.digest(); StringBuffer sb = new StringBuffer(""); for (int i = 0; i< rbytes.length; i++) { sb.append(Integer.toString((rbytes[i] & 0xff) + 0x100, 16).substring(1)); } if (shaVal.equals(sb.toString())) { resultant = ("\nFalse : " + "\nFound:\n" + sb.toString() + "|" + "\nHave:\n" + shaVal); } else { resultant = ("\nTrue : " + "\nFound:\n" + sb.toString() + "|" + "\nHave:\n" + shaVal); } return resultant; } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } } On a 2.2 Device I get average runtime of ~350ms, while on newer devices I get runtimes of 26-50ms which is substantially lower. I'm keeping in mind these devices are newer and have better hardware but am also wondering if the platform and the implementation affect performance much and if there is anything that could reduce runtimes on 2.2 devices. Note, the classes.dex of the .apk being accessed is roughly 4MB. Thanks!

    Read the article

  • android : sax Xml parsing

    - by Ram
    Team, I am facing some issue at the time of parsing the XML, but the same works in Java program... When I run the same code through android prgming its failing to parse... InputStream byteArrayInputStream = new ByteArrayInputStream( response.toString().getBytes()); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(byteArrayInputStream, xmlHandler); Facing the following error DTD handlers aren't supported Any help is greatly appreciated. Thanks, Ramesh

    Read the article

  • Uploading file to DropBox causing UnlinkedException

    - by Boardy
    I am currently working on android project and trying to enable DropBox functionality. I've selected the access type to App Only, and I can successfully authenticate and it creates an Apps directory and inside that creates a directory with the name of my app. When I then try to put a file in the DropBox directory it goes into the DropBoxException catch and in the logcat prints com.dropbox.client2.exception.DropboxUnlinkedException. I've done a google and from what I've seen this happens if the apps directory has been deleted and so authentication is required to be re-done, but this isn't the case, I have deleted it and I am putting the file straight after doing the authentication. Below is the code that retrieves the keys and stores the file on dropbox. AccessTokenPair tokens = getTokens(); UploadFile uploadFile = new UploadFile(context, common, this, mDBApi); uploadFile.execute(mDBApi); Below is the code for the getTokens method (don't think this would help but you never know) private AccessTokenPair getTokens() { AccessTokenPair tokens; SharedPreferences prefs = context.getSharedPreferences("prefs", 0); String key = prefs.getString("dropbox_key", ""); String secret = prefs.getString("dropbox_secret", ""); tokens = new AccessTokenPair(key, secret); return tokens; } Below is the class that extends the AsyncTask to perform the upload class UploadFile extends AsyncTask<DropboxAPI<AndroidAuthSession>, Void, bool> { Context context; Common common; Synchronisation sync; DropboxAPI<AndroidAuthSession> mDBApi; public UploadFile(Context context, Common common, Synchronisation sync, DropboxAPI<AndroidAuthSession> mDBApi) { this.context = context; this.common = common; this.sync = sync; this.mDBApi = mDBApi; } @Override protected bool doInBackground(DropboxAPI<AndroidAuthSession>... params) { try { File file = new File(Environment.getExternalStorageDirectory() + "/BoardiesPasswordManager/dropbox_sync.xml"); FileInputStream inputStream = new FileInputStream(file); Entry newEntry = mDBApi.putFile("android_sync.xml", inputStream, file.length(), null, null); common.showToastMessage("Successfully uploade Rev: " + newEntry.rev, Toast.LENGTH_LONG); } catch (IOException ex) { Log.e("DropBoxError", ex.toString()); } catch (DropboxException e) { Log.e("DropBoxError", e.toString()); e.printStackTrace(); } return null; } I have no idea why it would display the UnlinkedException so any help would be greatly appreciated.

    Read the article

  • Saving a stream to file

    - by Loadman
    Hi, I have a StreamReader object that I initialized with a stream, now I want to save this stream to disk (the stream may be a gif or jpg or pdf etc). SO my code so far is: StreamReader sr = new StreamReader(myOtherObject.InputStream); I need to save this to disk (I have the filename). In the future I may want to store this to sqlserver I have the encoding type also, which I will need if I store it to sql server right?

    Read the article

  • run shell command from java

    - by Aykut
    Hi, I am working on an application an have an issue about running shell command from java application. here is the code: public String execRuntime(String cmd) { Process proc = null; int inBuffer, errBuffer; int result = 0; StringBuffer outputReport = new StringBuffer(); StringBuffer errorBuffer = new StringBuffer(); try { proc = Runtime.getRuntime().exec(cmd); } catch (IOException e) { return ""; } try { response.status = 1; result = proc.waitFor(); } catch (InterruptedException e) { return ""; } if (proc != null && null != proc.getInputStream()) { InputStream is = proc.getInputStream(); InputStream es = proc.getErrorStream(); OutputStream os = proc.getOutputStream(); try { while ((inBuffer = is.read()) != -1) { outputReport.append((char) inBuffer); } while ((errBuffer = es.read()) != -1) { errorBuffer.append((char) errBuffer); } } catch (IOException e) { return ""; } try { is.close(); is = null; es.close(); es = null; os.close(); os = null; } catch (IOException e) { return ""; } proc.destroy(); proc = null; } if (errorBuffer.length() > 0) { logger .error("could not finish execution because of error(s)."); logger.error("*** Error : " + errorBuffer.toString()); return ""; } return outputReport.toString(); } but when i try to exec command like : /export/home/test/myapp -T "some argument" myapp reads "some argument" as two seperated arguments.but I want to read "some argument" as only a argument. when i directly run this command from terminal, it executed successfully. I tried '"some argument"' ,""some argument"" , "some\ argument" but did not work for me. how can i read this argument as one argument. Thnaks.

    Read the article

  • Java: Detecting image formate - resize (scale) and save as JPEG

    - by BoDiE2003
    This is the code I have, it actually works, not perfectly but it does, the problem is that the resized thumbnails are not pasting on the white Drawn rectangle, breaking the images aspect ratio, here is the code, could someone suggest me a fix for it, please? Thank you import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ImageScalerImageIoImpl implements ImageScaler { private static final String OUTPUT_FORMAT_ID = "jpeg"; // Re-scaling image public byte[] scaleImage(byte[] originalImage, int targetWidth, int targetHeight) { try { InputStream imageStream = new BufferedInputStream( new ByteArrayInputStream(originalImage)); Image image = (Image) ImageIO.read(imageStream); int thumbWidth = targetWidth; int thumbHeight = targetHeight; // Make sure the aspect ratio is maintained, so the image is not skewed double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } // Draw the scaled image BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); System.out.println("Thumb width Buffered: " + thumbWidth + " || Thumb height Buffered: " + thumbHeight); Graphics2D graphics2D = thumbImage.createGraphics(); // Use of BILNEAR filtering to enable smooth scaling graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); // graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // White Background graphics2D.setPaint(Color.WHITE); graphics2D.fill(new Rectangle2D.Double(0, 0, targetWidth, targetHeight)); graphics2D.fillRect(0, 0, targetWidth, targetHeight); System.out.println("Target width: " + targetWidth + " || Target height: " + targetHeight); // insert the resized thumbnail between X and Y of the image graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); System.out.println("Thumb width: " + thumbWidth + " || Thumb height: " + thumbHeight); // Write the scaled image to the outputstream ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(thumbImage, OUTPUT_FORMAT_ID, out); return out.toByteArray(); } catch (IOException ioe) { throw new ImageResizingException(ioe); } } }

    Read the article

  • sending and receiving with sockets in java?

    - by Darksole
    I am working on sending and receiving from clients and servers in java, and am stumped at the moment. the client socket is to contact a server at “localhost” port 4321. The client will receive a string from the server and alternate spelling the contents of this string with the server. For example, given the string “Bye Bye”, the client (which always begins sending the first letter) sends “B”, receives “y”, sends “e”, receives “ ”, sends “B”, receives “y”, sends “e”, and receives “done!”, which is the string that either client or server will send after the last letter from the original string is received. After “done!” is transmitted, both client and server close their communications. How would i go about getting the first string and then going back and forth sending and reciving letters that make the string, and when finished either send or get done!? import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Program2 { public static void goClient() throws UnknownHostException, IOException{ String server = "localhost"; int port = 4321; Socket socket = new Socket(server, port); InputStream inStream = socket.getInputStream(); OutputStream outStream = socket.getOutputStream(); Scanner in = new Scanner(inStream); PrintWriter out = new PrintWriter(outStream, true); String rec = ""; if(in.hasNext()){ rec = in.nextLine(); } char[] array = new char[rec.length()]; for(int i = 0; i < rec.length(); i++){ array[i] = rec.charAt(i); } while(in.hasNext()){ for(int x = 0; x < array.length + 1; x+=2){ String str = in.nextLine(); str = Character.toString(array[x]); out.println(str); } in.close(); socket.close(); } } }

    Read the article

  • Android Assets No Value Read?

    - by BahaiResearch.com
    AssetManager assets = myContext.getAssets(); String[] files = assets.list("MyFolder"); InputStream myInput = assets.open("MyFolder/" + files[0]); int i = myInput.read(); in this case 'i' is -1 meaning nothing read. Why would nothing be there if the file is there, the variable 'files' has the file as well. Do I need to do anything to the file I put into the Assets folder in get it to be readable?

    Read the article

  • Java: how to read BufferedReader faster

    - by Cata
    Hello, I want to optimize this code: InputStream is = rp.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String text = ""; String aux = ""; while ((aux = reader.readLine()) != null) { text += aux; } The thing is that i don't know how to read the content of the bufferedreader and copy it in a String faster than what I have above. I need to spend as little time as possible. Thank you

    Read the article

  • c# video equivalent to image.fromstream? Or changing the scope of the following script to allow vide

    - by Daniel
    The following is a part of an upload class in a c# script. I'm a php programmer, I've never messed with c# much but I'm trying to learn. This upload script will not handle anything except images, I need to adapt this class to handle other types of media also, or rewrite it all together. If I'm correct, I realize that using (Image image = Image.FromStream(file.InputStream)) basically says that the scope of the following is Image, only an image can be used or the object is discarded? And also that the variable image is being created from an Image from the file stream, which I understand to be, like... the $_FILES array in php? I dunno, I don't really care about making thumbnails right now either way, so if this can be taken out and still process the upload I'm totally cool with that, I just haven't had any luck getting this thing to take anything but images, even when commenting out that whole part of the class... protected void Page_Load(object sender, EventArgs e) { string dir = Path.Combine(Request.PhysicalApplicationPath, "files"); if (Request.Files.Count == 0) { // No files were posted Response.StatusCode = 500; } else { try { // Only one file at a time is posted HttpPostedFile file = Request.Files[0]; // Size limit 100MB if (file.ContentLength > 102400000) { // File too large Response.StatusCode = 500; } else { string id = Request.QueryString["userId"]; string[] folders = userDir(id); foreach (string folder in folders) { dir = Path.Combine(dir, folder); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); } string path = Path.Combine(dir, String.Concat(Request.QueryString["batchId"], "_", file.FileName)); file.SaveAs(path); // Create thumbnail int dot = path.LastIndexOf('.'); string thumbpath = String.Concat(path.Substring(0, dot), "_thumb", path.Substring(dot)); using (Image image = Image.FromStream(file.InputStream)) { // Find the ratio that will create maximum height or width of 100px. double ratio = Math.Max(image.Width / 100.0, image.Height / 100.0); using (Image thumb = new Bitmap(image, new Size((int)Math.Round(image.Width / ratio), (int)Math.Round(image.Height / ratio)))) { using (Graphics graphic = Graphics.FromImage(thumb)) { // Make sure thumbnail is not crappy graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.InterpolationMode = InterpolationMode.High; graphic.CompositingQuality = CompositingQuality.HighQuality; // JPEG ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1]; // 90% quality EncoderParameters encode = new EncoderParameters(1); encode.Param[0] = new EncoderParameter(Encoder.Quality, 90L); // Resize graphic.DrawImage(image, new Rectangle(0, 0, thumb.Width, thumb.Height)); // Save thumb.Save(thumbpath, codec, encode); } } } // Success Response.StatusCode = 200; } } catch { // Something went wrong Response.StatusCode = 500; } } }

    Read the article

  • Android Thumbnail Loading Problem

    - by y ramesh rao
    I'm using a thumbnail loader in my project the one mentioned below. The problem is that the it loads all the thumbnails properly except the ones who's size is of about 40K. When our back end is giving that sort of thumbnails are not generated and sometimes this eventually leads to a Crash too. What m I supposed to do with this ? public class ThumbnailManager { private final Map<String, Bitmap> drawableMap; public static Context context; private Resources res; private int thumbnail_size; public ThumbnailManager() { drawableMap = new HashMap<String, Bitmap >(); res = new Resources(context.getAssets(), null, null); thumbnail_size = res.getInteger(R.ThumbnailManager.THUMBNAIL_SIZE); } public Bitmap fetchBitmap(String urlString) { if(drawableMap.containsKey(urlString)) { return (drawableMap.get(urlString)); } //Log.d(getClass().getSimpleName(), " Image URL :: "+ urlString); try { InputStream is = fetch(urlString); android.util.Log.v("ThumbnailManager", "ThumbnailManager " + urlString); drawableMap.put(urlString, BitmapFactory.decodeStream(is));//Bitmap.createScaledBitmap(BitmapFactory.decodeStream(is), thumbnail_size, thumbnail_size, false)); return drawableMap.get(urlString); } catch(Exception e) { android.util.Log.v("EXCEPTION", "EXCEPTION" + urlString); return null; } } public void fetchBitmapOnThread(final String urlString, final ImageView imageView) { if(drawableMap.containsKey(urlString)) { imageView.setImageBitmap(drawableMap.get(urlString)); return; } if(urlString.compareTo("AUDIO") == 0) { Bitmap audioThumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.timeline_audio_thumb); drawableMap.put(urlString, Bitmap.createScaledBitmap(audioThumb, thumbnail_size, thumbnail_size, false)); imageView.setImageBitmap(drawableMap.get(urlString)); return; } final Handler handler = new Handler() { public void handleMessage(Message message) { imageView.setImageBitmap((Bitmap) message.obj); } }; Thread thread = new Thread() { public void run() { Bitmap urlBitmap = fetchBitmap(urlString); Message message = handler.obtainMessage(1, urlBitmap); handler.sendMessage(message); } }; thread.start(); } public InputStream fetch(String urlString) throws IOException, MalformedURLException { final URL url = new URL(urlString); final URLConnection conn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(true); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); return(conn.getInputStream()); } }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >