Search Results

Search found 268 results on 11 pages for 'fileinputstream'.

Page 9/11 | < Previous Page | 5 6 7 8 9 10 11  | Next Page >

  • How do I instantiate Class Dynamically in Java?

    - by kunjaan
    I have the class name stored in a property file. I know that the classes store will implement IDynamicLoad. How do I instantiate the class dynamically? Right now I have Properties foo = new Properties(); foo.load(new FileInputStream(new File("ClassName.properties"))); String class_name = foo.getProperty("class","DefaultClass"); //IDynamicLoad newClass = Class.forName(class_name).newInstance(); Does the newInstance only load compiled .class files? How do I load a Java Class that is not compiled?

    Read the article

  • android drawable changes sizes on screen when reading image from file

    - by Daniel Benedykt
    Hi I have an image on a private file. I read the file, create the drawable, and assign it to an ImageView. The ImageView has WRAP_CONTENT so the size is automatic. On 320x480 screens, the image looks good But on screens with more resolution and high density 480x800 or 480x854 (N1, droid) , when the image is for example 150x150, I see the image as 100x100. Of course it has something to do with the density but not sure how should I resolve this. This is my code: FileInputStream fis = this.openFileInput("icon.png"); icon = Drawable.createFromStream(fis, "icon"); fis.close(); imageView.setImageDrawable(icon); thanks

    Read the article

  • Java - ClassNotFoundException I have the class included, but why do I get an exception?

    - by aloh
    public static Reservation[] openBinaryFile( String fileName ) { Reservation [] objArray = null; try { ObjectInputStream inStream = new ObjectInputStream( new FileInputStream( fileName ) ); objArray = (Reservation[])inStream.readObject(); inStream.close(); } catch( ClassNotFoundException e ) { System.out.println( "Exception: ClassNotFoundException." ); } I have the class included, but why do I get an exception? The class is in the same package as the others. Why am I getting this exception?

    Read the article

  • How to send audio data from Java Applet to Rails controller

    - by cooldude
    Hi, I have to send the audio data in byte array obtain by recording from java applet at the client side to rails server at the controller in order to save. So, what encoding parameters at the applet side be used and in what form the audio data be converted like String or byte array so that rails correctly recieve data and then I can save that data at the rails in the file. As currently the audio file made by rails controller is not playing. It is the following ERROR : LAVF_header: av_open_input_stream() failed while playing with the mplayer. Here is the Java Code: package networksocket; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JApplet; import java.net.*; import java.io.*; import java.awt.event.*; import java.awt.*; import java.sql.*; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.util.Properties; import javax.swing.plaf.basic.BasicSplitPaneUI.BasicHorizontalLayoutManager; import sun.awt.HorizBagLayout; import sun.awt.VerticalBagLayout; import sun.misc.BASE64Encoder; /** * * @author mukand */ public class Urlconnection extends JApplet implements ActionListener { /** * Initialization method that will be called after the applet is loaded * into the browser. */ public BufferedInputStream in; public BufferedOutputStream out; public String line; public FileOutputStream file; public int bytesread; public int toread=1024; byte b[]= new byte[toread]; public String f="FINISH"; public String match; public File fileopen; public JTextArea jTextArea; public Button refreshButton; public HttpURLConnection urlConn; public URL url; OutputStreamWriter wr; BufferedReader rd; @Override public void init() { // TODO start asynchronous download of heavy resources //textField= new TextField("START"); //getContentPane().add(textField); JPanel p = new JPanel(); jTextArea= new JTextArea(1500,1500); p.setLayout(new GridLayout(1,1, 1,1)); p.add(new JLabel("Server Details")); p.add(jTextArea); Container content = getContentPane(); content.setLayout(new GridBagLayout()); // Used to center the panel content.add(p); jTextArea.setLineWrap(true); refreshButton = new java.awt.Button("Refresh"); refreshButton.reshape(287,49,71,23); refreshButton.setFont(new Font("Dialog", Font.PLAIN, 12)); refreshButton.addActionListener(this); add(refreshButton); Properties properties = System.getProperties(); properties.put("http.proxyHost", "netmon.iitb.ac.in"); properties.put("http.proxyPort", "80"); } @Override public void actionPerformed(ActionEvent e) { try { url = new URL("http://localhost:3000/audio/audiorecieve"); urlConn = (HttpURLConnection)url.openConnection(); //String login = "mukandagarwal:rammstein$"; //String encodedLogin = new BASE64Encoder().encodeBuffer(login.getBytes()); //urlConn.setRequestProperty("Proxy-Authorization",login); urlConn.setRequestMethod("POST"); // urlConn.setRequestProperty("Content-Type", //"application/octet-stream"); //urlConn.setRequestProperty("Content-Type","audio/mpeg");//"application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Type","application/x-www- form-urlencoded"); //urlConn.setRequestProperty("Content-Length", "" + // Integer.toString(urlParameters.getBytes().length)); urlConn.setRequestProperty("Content-Language", "UTF-8"); urlConn.setDoOutput(true); urlConn.setDoInput(true); byte bread[]=new byte[2048]; int iread; char c; String data=URLEncoder.encode("key1", "UTF-8")+ "="; //String data="key1="; FileInputStream fileread= new FileInputStream("//home//mukand//Hellion.ogg");//Dogs.mp3");//Desktop//mausam1.mp3"); while((iread=fileread.read(bread))!=-1) { //data+=(new String()); /*for(int i=0;i<iread;i++) { //c=(char)bread[i]; System.out.println(bread[i]); }*/ data+= URLEncoder.encode(new String(bread,iread), "UTF-8");//new String(new String(bread));// // data+=new String(bread,iread); } //urlConn.setRequestProperty("Content-Length",Integer.toString(data.getBytes().length)); System.out.println(data); //data+=URLEncoder.encode("mukand", "UTF-8"); //data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); //data="key1="; wr = new OutputStreamWriter(urlConn.getOutputStream());//urlConn.getOutputStream(); //if((iread=fileread.read(bread))!=-1) // wr.write(bread,0,iread); wr.write(data); wr.flush(); fileread.close(); jTextArea.append("Send"); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while ((line = rd.readLine()) != null) { jTextArea.append(line); } wr.close(); rd.close(); //jTextArea.append("click"); } catch (MalformedURLException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Urlconnection.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void start() { } @Override public void stop() { } @Override public void destroy() { } // TODO overwrite start(), stop() and destroy() methods } Here is the Rails controller function for recieving: def audiorecieve puts "///////////////////////////////////////******RECIEVED*******////" puts params[:key1]#+" "+params[:key2] data=params[:key1] #request.env('RAW_POST_DATA') file=File.new("audiodata.ogg", 'w') file.write(data) file.flush file.close puts "////**************DONE***********//////////////////////" end Please reply quickly

    Read the article

  • Traditional IO vs memory-mapped

    - by Senne
    I'm trying to illustrate the difference in performance between traditional IO and memory mapped files in java to students. I found an example somewhere on internet but not everything is clear to me, I don't even think all steps are nececery. I read a lot about it here and there but I'm not convinced about a correct implementation of neither of them. The code I try to understand is: public class FileCopy{ public static void main(String args[]){ if (args.length < 1){ System.out.println(" Wrong usage!"); System.out.println(" Correct usage is : java FileCopy <large file with full path>"); System.exit(0); } String inFileName = args[0]; File inFile = new File(inFileName); if (inFile.exists() != true){ System.out.println(inFileName + " does not exist!"); System.exit(0); } try{ new FileCopy().memoryMappedCopy(inFileName, inFileName+".new" ); new FileCopy().customBufferedCopy(inFileName, inFileName+".new1"); }catch(FileNotFoundException fne){ fne.printStackTrace(); }catch(IOException ioe){ ioe.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } public void memoryMappedCopy(String fromFile, String toFile ) throws Exception{ long timeIn = new Date().getTime(); // read input file RandomAccessFile rafIn = new RandomAccessFile(fromFile, "rw"); FileChannel fcIn = rafIn.getChannel(); ByteBuffer byteBuffIn = fcIn.map(FileChannel.MapMode.READ_WRITE, 0,(int) fcIn.size()); fcIn.read(byteBuffIn); byteBuffIn.flip(); RandomAccessFile rafOut = new RandomAccessFile(toFile, "rw"); FileChannel fcOut = rafOut.getChannel(); ByteBuffer writeMap = fcOut.map(FileChannel.MapMode.READ_WRITE,0,(int) fcIn.size()); writeMap.put(byteBuffIn); long timeOut = new Date().getTime(); System.out.println("Memory mapped copy Time for a file of size :" + (int) fcIn.size() +" is "+(timeOut-timeIn)); fcOut.close(); fcIn.close(); } static final int CHUNK_SIZE = 100000; static final char[] inChars = new char[CHUNK_SIZE]; public static void customBufferedCopy(String fromFile, String toFile) throws IOException{ long timeIn = new Date().getTime(); Reader in = new FileReader(fromFile); Writer out = new FileWriter(toFile); while (true) { synchronized (inChars) { int amountRead = in.read(inChars); if (amountRead == -1) { break; } out.write(inChars, 0, amountRead); } } long timeOut = new Date().getTime(); System.out.println("Custom buffered copy Time for a file of size :" + (int) new File(fromFile).length() +" is "+(timeOut-timeIn)); in.close(); out.close(); } } When exactly is it nececary to use RandomAccessFile? Here it is used to read and write in the memoryMappedCopy, is it actually nececary just to copy a file at all? Or is it a part of memorry mapping? In customBufferedCopy, why is synchronized used here? I also found a different example that -should- test the performance between the 2: public class MappedIO { private static int numOfInts = 4000000; private static int numOfUbuffInts = 200000; private abstract static class Tester { private String name; public Tester(String name) { this.name = name; } public long runTest() { System.out.print(name + ": "); try { long startTime = System.currentTimeMillis(); test(); long endTime = System.currentTimeMillis(); return (endTime - startTime); } catch (IOException e) { throw new RuntimeException(e); } } public abstract void test() throws IOException; } private static Tester[] tests = { new Tester("Stream Write") { public void test() throws IOException { DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(new File("temp.tmp")))); for(int i = 0; i < numOfInts; i++) dos.writeInt(i); dos.close(); } }, new Tester("Mapped Write") { public void test() throws IOException { FileChannel fc = new RandomAccessFile("temp.tmp", "rw") .getChannel(); IntBuffer ib = fc.map( FileChannel.MapMode.READ_WRITE, 0, fc.size()) .asIntBuffer(); for(int i = 0; i < numOfInts; i++) ib.put(i); fc.close(); } }, new Tester("Stream Read") { public void test() throws IOException { DataInputStream dis = new DataInputStream( new BufferedInputStream( new FileInputStream("temp.tmp"))); for(int i = 0; i < numOfInts; i++) dis.readInt(); dis.close(); } }, new Tester("Mapped Read") { public void test() throws IOException { FileChannel fc = new FileInputStream( new File("temp.tmp")).getChannel(); IntBuffer ib = fc.map( FileChannel.MapMode.READ_ONLY, 0, fc.size()) .asIntBuffer(); while(ib.hasRemaining()) ib.get(); fc.close(); } }, new Tester("Stream Read/Write") { public void test() throws IOException { RandomAccessFile raf = new RandomAccessFile( new File("temp.tmp"), "rw"); raf.writeInt(1); for(int i = 0; i < numOfUbuffInts; i++) { raf.seek(raf.length() - 4); raf.writeInt(raf.readInt()); } raf.close(); } }, new Tester("Mapped Read/Write") { public void test() throws IOException { FileChannel fc = new RandomAccessFile( new File("temp.tmp"), "rw").getChannel(); IntBuffer ib = fc.map( FileChannel.MapMode.READ_WRITE, 0, fc.size()) .asIntBuffer(); ib.put(0); for(int i = 1; i < numOfUbuffInts; i++) ib.put(ib.get(i - 1)); fc.close(); } } }; public static void main(String[] args) { for(int i = 0; i < tests.length; i++) System.out.println(tests[i].runTest()); } } I more or less see whats going on, my output looks like this: Stream Write: 653 Mapped Write: 51 Stream Read: 651 Mapped Read: 40 Stream Read/Write: 14481 Mapped Read/Write: 6 What is makeing the Stream Read/Write so unbelievably long? And as a read/write test, to me it looks a bit pointless to read the same integer over and over (if I understand well what's going on in the Stream Read/Write) Wouldn't it be better to read int's from the previously written file and just read and write ints on the same place? Is there a better way to illustrate it? I've been breaking my head about a lot of these things for a while and I just can't get the whole picture..

    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

  • pylucene: install error

    - by Pradeep
    I am trying to install Pylucene (pylucene-3.3-3-src.tar.gz) on my ubuntu linux 11.10. I have python 2.7.2. I was able to compile JCC (I think) because I didnt see any error when I installed it. When I tried to install Pylucene I get the following error. Can someone help? Thanks. ICU not installed /usr/bin/python -m jcc --shared --jar lucene-java-3.3/lucene/build/lucene-core-3.3.jar --jar lucene-java-3.3/lucene/build/contrib/analyzers/common/lucene-analyzers-3.3.jar --jar lucene-java-3.3/lucene/build/contrib/memory/lucene-memory-3.3.jar --jar lucene-java-3.3/lucene/build/contrib/highlighter/lucene-highlighter-3.3.jar --jar build/jar/extensions.jar --jar lucene-java-3.3/lucene/build/contrib/queries/lucene-queries-3.3.jar --jar lucene-java-3.3/lucene/build/contrib/grouping/lucene-grouping-3.3.jar --package java.lang java.lang.System java.lang.Runtime --package java.util java.util.Arrays java.util.HashMap java.util.HashSet java.text.SimpleDateFormat java.text.DecimalFormat java.text.Collator --package java.util.regex --package java.io java.io.StringReader java.io.InputStreamReader java.io.FileInputStream --exclude org.apache.lucene.queryParser.Token --exclude org.apache.lucene.queryParser.TokenMgrError --exclude org.apache.lucene.queryParser.QueryParserTokenManager --exclude org.apache.lucene.queryParser.ParseException --exclude org.apache.lucene.search.regex.JakartaRegexpCapabilities --exclude org.apache.regexp.RegexpTunnel --exclude org.apache.lucene.analysis.cn.smart.AnalyzerProfile --python lucene --mapping org.apache.lucene.document.Document 'get:(Ljava/lang/String;)Ljava/lang/String;' --mapping java.util.Properties 'getProperty:(Ljava/lang/String;)Ljava/lang/String;' --sequence java.util.AbstractList 'size:()I' 'get:(I)Ljava/lang/Object;' --rename org.apache.lucene.search.highlight.SpanScorer=HighlighterSpanScorer --version 3.3 --module python/collections.py --module python/ICUNormalizer2Filter.py --module python/ICUFoldingFilter.py --module python/ICUTransformFilter.py --files 3 --build /usr/bin/python: No module named jcc make: *** [compile] Error 1 Here is my Makefile configuration which I uncommented PREFIX_PYTHON=/usr ANT=ant PYTHON=$(PREFIX_PYTHON)/bin/python JCC=$(PYTHON) -m jcc --shared NUM_FILES=3

    Read the article

  • Improve XPath efficiency for repeated, parameterized queries

    - by Chris Allan
    Hi, I am repeatedly performing the following XPath query (though parameterized by 'keywordText') around 40,000 times: String query = SystemGlobal.YAHOO_KEYWORDSSUBNODE + "/" + SystemGlobal.YAHOO_KEYWORDNODE + "[" + SystemGlobal.YAHOO_ATTRKEYPHRASE + "='" + keywordText + "']"; CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); NodeIterator nl = cachedXPathAPI.selectNodeIterator(doc.getElementsByTagName(SystemGlobal.YAHOO_KEYWORDSROOT).item(0), query); Node n; if ((n = nl.nextNode()) != null) { keyword.setKeywordId(Long.parseLong(cachedXPathAPI.selectSingleNode(n, SystemGlobal.YAHOO_ATTRKEYID).getTextContent())); keyword.setKeyPhrase(cachedXPathAPI.selectSingleNode(n, SystemGlobal.YAHOO_ATTRKEYPHRASE).getTextContent()); keyword.setStatus(mapStatus(cachedXPathAPI.selectSingleNode(n, SystemGlobal.YAHOO_ATTRSTATUS).getTextContent())); keyword.setCampaignId(Long.parseLong(cachedXPathAPI.selectSingleNode(n, "../../" + SystemGlobal.YAHOO_ATTRCAMPAIGNID).getTextContent())); keyword.setAdGroupId(Long.parseLong(cachedXPathAPI.selectSingleNode(n, "../" + SystemGlobal.YAHOO_ATTRADGROUPID).getTextContent())); On the first run of the script, all 40,000 runs of this piece of code will have nl.nextNode() == null, and everything runs quite quickly. However, on the following runs, when nl.nextNode() != null, then things slow down a lot - this takes around an additional 40min to run (whereas the first run takes maybe 1 minute). Oh, and the doc is constructed like so: InputSource in = new InputSource(new FileInputStream(filename)); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); doc = dfactory.newDocumentBuilder().parse(in); I tried including the following lines reportEvaluator = new XPathEvaluatorImpl(reportDoc); reportResolver = reportEvaluator.createNSResolver(reportDoc); and rather creating a NodeIterator, instead creating an XPathResult: XPathResult result = (XPathResult)reportEvaluator.evaluate(query, doc.getElementsByTagName(SystemGlobal.YAHOO_KEYWORDSROOT).item(0), reportResolver, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null); however this ran even slower Is there a way in which I can speed up the running of this script? I have seen references to precompiled queries, though I haven't seen many actual details. Also, as seen in the code, I am using CachedXPathAPI, though the benefit for this case is not so great. Any help is much appreciated! Chris Allan

    Read the article

  • JasperReport Issue using with struts2 - getting null in final PDF file

    - by Nirmal
    Hello, i am writing my jasper report problem with struts2. Following is the code that i am trying to execute : struts.xml contains : <action name="myJasperTest1" class="temp.JasperAction1"> <result name="success" type="jasper"> <param name="location">/jasper/our_compiled_template.jasper</param> <param name="dataSource">myList</param> <param name="format">PDF</param> </result> </action> My JasperAction1 contains : import java.util.ArrayList; import java.util.List; import com.sufalam.business.model.util.LegacyJasperInputStream; import net.sf.jasperreports.engine.JasperCompileManager; import com.opensymphony.xwork2.ActionSupport; import com.sufalam.business.finance.model.bean.Account; import java.io.FileInputStream; import net.sf.jasperreports.engine.design.JasperDesign; import net.sf.jasperreports.engine.xml.JRXmlLoader; public class JasperAction1 extends ActionSupport { /** List to use as our JasperReports dataSource. */ private List<Account> myList; public String execute() throws Exception { // Create some imaginary persons. Account a1 = new Account(); Account a2 = new Account(); a1.setId(77); a1.setName("aaa"); a2.setId(88); a2.setName("bbb"); // Store people in our dataSource list (normally would come from database). myList = new ArrayList<Account>(); myList.add(a1); myList.add(a2); // Normally we would provide a pre-compiled .jrxml file // or check to make sure we don't compile on every request. try { JasperDesign design = JRXmlLoader.load( new LegacyJasperInputStream(new FileInputStream("F://backup//backup 26-5(final acegi)//SufalamERP//build//web//jasper//report2.jrxml"))); JasperCompileManager.compileReportToFile(design,"F://backup//backup 26-5(final acegi)//SufalamERP//build//web//jasper//our_compiled_template1.jasper"); } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; } public List<Account> getMyList() { return myList; } } I am using ireport plugin of Netbeans for generation .jrxml file. After Designing my page using IReport wizard my our_jasper_template.jrxml file contains following code : <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="null" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"> <queryString language="SQL"> <![CDATA[SELECT account_master."name" AS account_master_name, account_master."id" AS account_master_id FROM "public"."account_master" account_master]]> </queryString> <field name="account_master_name" class="java.lang.String"> <fieldDescription><![CDATA[]]></fieldDescription> </field> <field name="account_master_id" class="java.lang.Integer"> <fieldDescription><![CDATA[]]></fieldDescription> </field> <background> <band/> </background> <title> <band height="58"> <line> <reportElement x="0" y="8" width="555" height="1"/> </line> <line> <reportElement positionType="FixRelativeToBottom" x="0" y="51" width="555" height="1"/> </line> <staticText> <reportElement x="65" y="13" width="424" height="35"/> <textElement textAlignment="Center"> <font size="26" isBold="true"/> </textElement> <text><![CDATA[Classic template]]></text> </staticText> </band> </title> <pageHeader> <band/> </pageHeader> <columnHeader> <band/> </columnHeader> <detail> <band height="40"> <staticText> <reportElement x="0" y="0" width="139" height="20"/> <textElement> <font size="12"/> </textElement> <text><![CDATA[account_master_name]]></text> </staticText> <textField> <reportElement x="139" y="0" width="416" height="20"/> <textElement> <font size="12"/> </textElement> <textFieldExpression class="java.lang.String"><![CDATA[$F{account_master_name}]]></textFieldExpression> </textField> <staticText> <reportElement x="0" y="20" width="139" height="20"/> <textElement> <font size="12"/> </textElement> <text><![CDATA[account_master_id]]></text> </staticText> <textField> <reportElement x="139" y="20" width="416" height="20"/> <textElement> <font size="12"/> </textElement> <textFieldExpression class="java.lang.Integer"><![CDATA[$F{account_master_id}]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band/> </columnFooter> <pageFooter> <band height="26"> <textField evaluationTime="Report" pattern="" isBlankWhenNull="false"> <reportElement key="textField" x="516" y="6" width="36" height="19" forecolor="#000000" backcolor="#FFFFFF"/> <box> <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement> <font size="10"/> </textElement> <textFieldExpression class="java.lang.String"><![CDATA["" + $V{PAGE_NUMBER}]]></textFieldExpression> </textField> <textField pattern="" isBlankWhenNull="false"> <reportElement key="textField" x="342" y="6" width="170" height="19" forecolor="#000000" backcolor="#FFFFFF"/> <box> <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement textAlignment="Right"> <font size="10"/> </textElement> <textFieldExpression class="java.lang.String"><![CDATA["Page " + $V{PAGE_NUMBER} + " of "]]></textFieldExpression> </textField> <textField pattern="" isBlankWhenNull="false"> <reportElement key="textField" x="1" y="6" width="209" height="19" forecolor="#000000" backcolor="#FFFFFF"/> <box> <topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> <rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/> </box> <textElement> <font size="10"/> </textElement> <textFieldExpression class="java.util.Date"><![CDATA[new Date()]]></textFieldExpression> </textField> </band> </pageFooter> <summary> <band/> </summary> </jasperReport> Now the problem i am facing is when i execute this action class it gives me following output as pdf format :

    Read the article

  • android DES decrypt file : pad block corrupted

    - by Kenny Chang
    public class TestDES { Key key; public TestDES(String str) { getKey(str); } public void getKey(String strKey) { try { KeyGenerator _generator = KeyGenerator.getInstance("DES"); _generator.init(new SecureRandom(strKey.getBytes())); this.key = _generator.generateKey(); _generator = null; } catch (Exception e) { throw new RuntimeException("Error initializing SqlMap class. Cause: " + e); } } public void decrypt(String file, String dest) throws Exception { Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, this.key); InputStream is = new FileInputStream(file); OutputStream out = new FileOutputStream(dest); CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[1024 * 1024 * 6]; int r; while ((r = is.read(buffer)) >= 0) { cos.write(buffer, 0, r); } cos.close();a out.close(); is.close(); } } The code works well on PC JAVA Program, but not on android.The error "pad block corrupted" happended at 'cos.close();' LogCat shows:" 03-10 07:43:04.431: WARN/System.err(23765): java.io.IOException: pad block corrupted 03-10 07:43:04.460: WARN/System.err(23765): at javax.crypto.CipherOutputStream.close(CipherOutputStream.java:157) "

    Read the article

  • Texture loading at joGL

    - by Nour
    hi I've been trying to load a bmp picture to use it as a texture at my program I've used a IOstream Class to extend DataInputStream to read the pixels at the photo with this code "based on a texture loader code for c++ " : //class Data members public static int BMPtextures[]; public static int BMPtexCount = 30; public static int currentTextureID = 0; //loading methode static int loadBMPTexture(int index, String fileName, GL gl) { try { IOStream wdis = new IOStream(fileName); wdis.skipBytes(18); int width = wdis.readIntW(); int height = wdis.readIntW(); wdis.skipBytes(28); byte buf[] = new byte[wdis.available()]; wdis.read(buf); wdis.close(); gl.glBindTexture(GL.GL_TEXTURE_2D, BMPtextures[index]); gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, 3, width, height, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, buf); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); currentTextureID = index; return currentTextureID; } catch (IOException ex) { // Utils.msgBox("File Error\n" + fileName, "Error", Utils.MSG_WARN); return -1; } } and IOStream code : public class IOStream extends DataInputStream { public IOStream(String file) throws FileNotFoundException { super(new FileInputStream(file)); } public short readShortW() throws IOException { return (short)(readUnsignedByte() + readUnsignedByte() * 256); } public int readIntW() throws IOException { return readShortW() + readShortW() * 256 * 256; } void read(Buffer[] buf) { } } and the calling: GTexture.loadBMPTexture(1,"/BasicJOGL/src/basicjogl/data/Font.bmp",gl); after debugging I figured out that when it come to this line : IOStream wdis = new IOStream(fileName); an IOExeption occurred and it's a dispatchException .. what this impose to mean ?? and how can I solve it ? by the way i tried to : 1- use \ and \ and / and // 2- change the path of the photo and take all the path from c:\ to the photoname.bmp 3- rename the photo using numbers like 1.bmp but nothing seems to work :(

    Read the article

  • RSA C# Encrypt Java Decrypt

    - by user353030
    Hi guys, In my program (server side - Java) I've created keystore file, with command: keytool -genkey -alias myalias -keyalg RSA -validity 10000 -keystore my.keystore and exported related X509 certificate with: keytool -export -alias myalias -file cert.cer -keystore my.keystore After I saved cert.cer on client side (C#) and I write this code: X509Certificate2 x509 = new X509Certificate2(); byte[] rawData = ReadFile("mycert.cer"); x509.Import(rawData); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key; byte[] plainbytes = System.Text.Encoding.ASCII.GetBytes("My Secret"); byte[] cipherbytes = rsa.Encrypt(plainbytes, true); String cipherHex = convertToHex(cipherContent); byte[] byteArray = encoding.GetBytes(cipherHex); .... I write this Java code on server side: keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(new FileInputStream("C:\\my.keystore"), "mypass".toCharArray()); Key key = keyStore.getKey("myalias", "mypass".toCharArray()); if (key instanceof PrivateKey) { Certificate cert = keyStore.getCertificate("myalias"); PublicKey pubKey = cert.getPublicKey(); privKey = (PrivateKey)key; } byte[] toDecodeBytes = new BigInteger(encodeMessageHex, 16).toByteArray(); Cipher decCipher = Cipher.getInstance("RSA"); decCipher.init(Cipher.DECRYPT_MODE, privKey); byte[] decodeMessageBytes = decCipher.doFinal(toDecodeBytes); String decodeMessageString = new String(decodeMessageBytes); I receive this error: javax.crypto.BadPaddingException: Data must start with zero Can you help me, please? Thanks thanks,

    Read the article

  • File Format DOS/Unix/MAC code sample

    - by mac
    I have written the following method to detemine whether file in question is formatted with DOS/ MAC, or UNIX line endings. I see at least 1 obvious issue: 1. i am hoping that i will get the EOL on the first run, say within first 1000 bytes. This may or may not happen. I ask you to review this and suggest improvements which will lead to hardening the code and making it more generic. THANK YOU. new FileFormat().discover(fileName, 0, 1000); and then public void discover(String fileName, int offset, int depth) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName)); FileReader a = new FileReader(new File(fileName)); byte[] bytes = new byte[(int) depth]; in.read(bytes, offset, depth); a.close(); in.close(); int thisByte; int nextByte; boolean isDos = false; boolean isUnix = false; boolean isMac = false; for (int i = 0; i < (bytes.length - 1); i++) { thisByte = bytes[i]; nextByte = bytes[i + 1]; if (thisByte == 10 && nextByte != 13) { isDos = true; break; } else if (thisByte == 13) { isUnix = true; break; } else if (thisByte == 10) { isMac = true; break; } } if (!(isDos || isMac || isUnix)) { discover(fileName, offset + depth, depth + 1000); } else { // do something clever } }

    Read the article

  • Retrieve data from .dat file.

    - by Zach
    We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception when we are accessing other objects using a "for" loop. File file=null; FileOutputStream fos=null; BufferedOutputStream bos=null; ObjectOutputStream oos=null; try{ file=new File("account4.dat"); fos=new FileOutputStream(file,true); bos=new BufferedOutputStream(fos); oos=new ObjectOutputStream(bos); oos.writeObject(m); System.out.println("object serialized"); amlist=new MemberAccountList(); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } Reading objects: try{ MemberAccount m1; file=new File("account4.dat");//add your code here fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); System.out.println(ois.readObject()); while(ois.readObject()!=null){ m1=(MemberAccount)ois.readObject(); System.out.println(m1.toString()); }/mList.addElement(m1); // Here we have the issue throwing null pointer exception Enumeration elist=mList.elements(); while(elist.hasMoreElements()){ obj=elist.nextElement(); System.out.println(obj.toString()); }/ } catch(ClassNotFoundException e){ } catch(EOFException e){ System.out.println("end"); } catch(Exception ex){ ex.printStackTrace(); }

    Read the article

  • Convert 4 bytes to int

    - by Oscar Reyes
    I'm reading a binary file like this: InputStream in = new FileInputStream( file ); byte[] buffer = new byte[1024]; while( ( in.read(buffer ) > -1 ) { int a = // ??? } What I want to do it to read up to 4 bytes and create a int value from those but, I don't know how to do it. I kind of feel like I have to grab 4 bytes at a time, and perform one "byte" operation ( like << & FF and stuff like that ) to create the new int What's the idiom for this? EDIT Ooops this turn out to be a bit more complex ( to explain ) What I'm trying to do is, read a file ( may be ascii, binary, it doesn't matter ) and extract the integers it may have. For instance suppose the binary content ( in base 2 ) : 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000010 The integer representation should be 1 , 2 right? :- / 1 for the first 32 bits, and 2 for the remaining 32 bits. 11111111 11111111 11111111 11111111 Would be -1 and 01111111 11111111 11111111 11111111 Would be Integer.MAX_VALUE ( 2147483647 )

    Read the article

  • Why ClassCastException on JMS ConnectionFactory lookup in JNDI?

    - by Derek Mahar
    What might be the cause of the following ClassCastException in a standalone JMS client application when it attempts to retrieve a connection factory from the JNDI provider? Exception in thread "main" java.lang.ClassCastException: javax.naming.Reference cannot be cast to javax.jms.ConnectionFactory Here is an abbreviated version of the JMS client that includes only its start() and stop() methods. The exception occurs on the first line in method start() which attempts to retrieve the connection factory from the JNDI provider, a remote LDAP server. The JMS connection factory and destination objects are on a remote JMS server. class JmsClient { private ConnectionFactory connectionFactory; private Connection connection; private Session session; private MessageConsumer consumer; private Topic topic; public void stop() throws JMSException { consumer.close(); session.close(); connection.close(); } public void start(Context context, String connectionFactoryName, String topicName) throws NamingException, JMSException { // ClassCastException occurs when retrieving connection factory. connectionFactory = (ConnectionFactory) context.lookup(connectionFactoryName); connection = connectionFactory.createConnection("username","password"); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); topic = (Topic) context.lookup(topicName); consumer = session.createConsumer(topic); connection.start(); } private static Context getInitialContext() throws NamingException, IOException { String filename = "context.properties"; Properties props = new Properties(); props.load(new FileInputStream(filename)); return new InitialContext(props); } }

    Read the article

  • Avoiding shutdown hook

    - by meryl
    Through the following code I can play and cut and audio file. Is there any other way to avoid using a shutdown hook? The problem is that whenever I push the cut button , the file doesn't get saved until I close the application thanks ...................... void play_cut() { try { // First, we get the format of the input file final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType(); // Then, we get a clip for playing the audio. c = AudioSystem.getClip(); // We get a stream for playing the input file. AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio); // We use the clip to open (but not start) the input stream c.open(ais); // We get the format of the audio codec (not the file format we got above) final AudioFormat audioFormat = ais.getFormat(); // We add a shutdown hook, an anonymous inner class. Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { // We're now in the hook, which means the program is shutting down. // You would need to use better exception handling in a production application. try { // Stop the audio clip. c.stop(); // Create a new input stream, with the duration set to the frame count we reached. Note that we use the previously determined audio format AudioInputStream startStream = new AudioInputStream(new FileInputStream(inputAudio), audioFormat, c.getLongFramePosition()); // Write it out to the output file, using the same file type. AudioSystem.write(startStream, fileType, outputAudio); } catch(IOException e) { e.printStackTrace(); } } }); // After setting up the hook, we start the clip. c.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } }// end play_cut ......................

    Read the article

  • read text file from phone memory in android

    - by Sudhakar
    Hi..I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator. My code is.. public class PhonememAct extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv=(TextView)findViewById(R.id.tv); FileOutputStream fos = null; try { fos = openFileOutput("Test.txt", Context.MODE_PRIVATE); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { fos.write("Hai..".getBytes()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } FileInputStream fis = null; try { fis = openFileInput("Test.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int c; try { while((c=fis.read())!=-1) { tv.setText(c); setContentView(tv); //k += (char)c; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Thanks in adv.

    Read the article

  • Beginner: Restore previously serialized JFrame-object, how?

    - by elementz
    Hi all. I have managed to serialize my very basic GUI-object containing a JTextArea and a few buttons to a file 'test.ser'. Now, I would like to completely restore the previously saved state from 'test.ser', but seem to have a misconception of how to properly deserialize an objects state. The class MyFrame creates the JFrame and serializes it. Now I tried to deserialize like so: public class Deserialize { static Deserialize ds; MyFrame frame; public static void main(String[] args) { try { ds.deserialize(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void deserialize() throws ClassNotFoundException { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser")); frame = (MyFrame) ois.readObject(); ois.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Maybe somebody could point me into the direction where my misconception is? Thx in advance!

    Read the article

  • why the main method are not covered? urgent, please help me

    - by Mike.Huang
    main method: public static void main(String[] args) throws Exception { if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS) { System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR"); } String configXML = args[0]; String packageXML = args[1]; String xfr = args[2]; AutoConfigCompiler compiler = new AutoConfigCompiler(); compiler.setConfigDocument(loadDocument(configXML)); compiler.setPackageInfoDoc(loadDocument(packageXML)); // compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml")); compiler.compileModel(xfr); } private static Document loadDocument(String fileName) throws Exception { TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName()); InputSource source = new InputSource(new FileInputStream(fileName)); parser.parse(source); return parser.getDocument(); } testcase: @Test public void testCompileModel() throws Exception { // construct parameters URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml"); URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml"); File tmpFile = new File("Ford_2008_Mustang_tmp.xfr"); if(!tmpFile.exists()) { tmpFile.createNewFile(); } String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()}; try { // test main method XFRCompiler.main(args); } catch (Exception e) { assertTrue(true); } try { // test args length is less than 3 XFRCompiler.main(new String[]{"",""}); } catch (Exception e) { assertTrue(true); } tmpFile.delete(); } coverage outputs displayed as the lines from “String configXML = args[0];" in main method are not covered

    Read the article

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

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

    Read the article

  • Download dynamic file with GWT

    - by Maksim
    I have a GWT page where user enter data (start date, end date, etc.), then this data goes to the server via RPC call. On the server I want to generate Excel report with POI and let user save that file on their local machine. This is my test code to stream file back to the client but for some reason I think it does not know how to stream file to the client when I'm using RPC: public class ReportsServiceImpl extends RemoteServiceServlet implements ReportsService { public String myMethod(String s) { File f = new File("/excelTestFile.xls"); String filename = f.getName(); int length = 0; try { HttpServletResponse resp = getThreadLocalResponse(); ServletOutputStream op = resp.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); resp.setContentType("application/octet-stream"); resp.setContentLength((int) f.length()); resp.setHeader("Content-Disposition", "attachment; filename*=\"utf-8''" + filename + ""); byte[] bbuf = new byte[1024]; DataInputStream in = new DataInputStream(new FileInputStream(f)); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } in.close(); op.flush(); op.close(); } catch (Exception ex) { ex.printStackTrace(); } return "Server says: " + filename; } } I've red somewhere on internet that you can't do file stream with RPC and I have to use Servlet for that. Is there any example of how to use Servlet and how to call that servlet from ReportsServiceImpl. Do I really need to make a servlet or it is possible to stream it back with my RPC?

    Read the article

  • How to read data from file(.dat) in append mode

    - by govardhan
    We have an application which requires us to read data from a file (.dat) dynamically using deserialization. We are actually getting first object and it throws null pointer exception and "java.io.StreamCorruptedException:invalid type code:AC" when we are accessing other objects using a "for" loop. File file=null; FileOutputStream fos=null; BufferedOutputStream bos=null; ObjectOutputStream oos=null; try{ file=new File("account4.dat"); fos=new FileOutputStream(file,true); bos=new BufferedOutputStream(fos); oos=new ObjectOutputStream(bos); oos.writeObject(m); System.out.println("object serialized"); amlist=new MemberAccountList(); oos.close(); } catch(Exception ex){ ex.printStackTrace(); } Reading objects: try{ MemberAccount m1; file=new File("account4.dat");//add your code here fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); System.out.println(ois.readObject()); **while(ois.readObject()!=null){ m1=(MemberAccount)ois.readObject(); System.out.println(m1.toString()); }/*mList.addElement(m1);** // Here we have the issue throwing null pointer exception Enumeration elist=mList.elements(); while(elist.hasMoreElements()){ obj=elist.nextElement(); System.out.println(obj.toString()); }*/ } catch(ClassNotFoundException e){ } catch(EOFException e){ System.out.println("end"); } catch(Exception ex){ ex.printStackTrace(); }

    Read the article

  • Graphing the pitch (frequency) of a sound

    - by Coronatus
    I want to plot the pitch of a sound into a graph. Currently I can plot the amplitude. The graph below is created by the data returned by getUnscaledAmplitude(): AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file))); byte[] bytes = new byte[(int) (audioInputStream.getFrameLength()) * (audioInputStream.getFormat().getFrameSize())]; audioInputStream.read(bytes); // Get amplitude values for each audio channel in an array. graphData = type.getUnscaledAmplitude(bytes, this); public int[][] getUnscaledAmplitude(byte[] eightBitByteArray, AudioInfo audioInfo) { int[][] toReturn = new int[audioInfo.getNumberOfChannels()][eightBitByteArray.length / (2 * audioInfo. getNumberOfChannels())]; int index = 0; for (int audioByte = 0; audioByte < eightBitByteArray.length;) { for (int channel = 0; channel < audioInfo.getNumberOfChannels(); channel++) { // Do the byte to sample conversion. int low = (int) eightBitByteArray[audioByte]; audioByte++; int high = (int) eightBitByteArray[audioByte]; audioByte++; int sample = (high << 8) + (low & 0x00ff); if (sample < audioInfo.sampleMin) { audioInfo.sampleMin = sample; } else if (sample > audioInfo.sampleMax) { audioInfo.sampleMax = sample; } toReturn[channel][index] = sample; } index++; } return toReturn; } But I need to show the audio's pitch, not amplitude. Fast Fourier transform appears to get the pitch, but it needs to know more variables than the raw bytes I have, and is very complex and mathematical. Is there a way I can do this?

    Read the article

  • JSP Upload File Java.lang.NullPointer

    - by newbie123
    I want to develope upload and download file from server. Upload.html <form action="/UploadFile/UploadFile" method="POST" enctype="multipart/form-data">Select a file: <input type="submit" name="button" /> <input type="file" name="first"></form> UploadFile.servlet protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String temp = request.getParameter("first"); System.out.println(temp); File origFile = new File(temp); FileOutputStream out = new FileOutputStream(request.getContextPath() + "pdtImages/" + "FirstFile"); InputStream ins = new FileInputStream(origFile); try { System.out.println(request.getContextPath()); byte[] buf = new byte[1024]; int len; while ((len = ins.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } When I submitted the file I got null pointer error message. I not very familiar with jsp can anybody help me? I want to store the file to the server directory.

    Read the article

< Previous Page | 5 6 7 8 9 10 11  | Next Page >