String to inputStream

Hi I'm trying to "convert a string to an inputstream. I'm working with the JTidy API which needs an inputstream for doing the parseDOM(var,var) method, everything works fine when my data comes from a file and when I use FileInputStream but it wont work with the InputStream.
It looks to me that the InputStream is empty. What I'm basically doing is:
String myInputStream = "blahdiblah";
try{
System.out.println("myInputStream:" + + myInputStream.read()); // gives me 98 the value of the first char
}catch( Exception e ) {
System.err.println("error:" + e.toString() );
InputStream in = null;
StreamSource myStreamSource = new StreamSource(myInputStream);
in = myStreamSource.getInputStream();
try{
System.out.println("1 test" + + in.read()); // gives me nothing back, while it should give 98
}catch( Exception e ) {
System.err.println("error:" + e.toString() );
Why does the first read-method returns the Decimal ASCII of the letter "b" and the second does not?
Can anyone tell me what I'm doing wrong? I'm not really familiar with these streaming stuff, any help would be great !

String data = "sfgafgagafg";
ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes())

Similar Messages

  • Converting string into inputstream and outputstream Jsch (ssh connection)

    hi,
    I'm not really sure if this is the place where i should ask this, but if it is so then tell me!
    So my problem is that everything works just fine with input output streams like in this code, but i need to change this input stream into string messadge(Which would work!!)
    The main problem is not that i can't change string to inputstream, but that when i use inputstream every commands works, and when i try to do the same with sting>inputstream this doesn't work...
    unfortunatelly newgrp server; or newgrp doesn't rerally work just frezzes :/
    anyway i solved the initial problem, because Jsch have two (probably more methods of sending info to unix server, but because there is no documentation htere no way to know :D)
    methods of sending info to server : exec and shell , the exec sends one command and only works with commands like date;ls... now the shell can easily send any type of command including newgrp server1, and everything works :)
    so we connect to the server(passw,user,host) then excecute commands, this code works perfectle but the commented code// doesn't work :
    JSch jsch=new JSch();
    String host=null;
    String user="me1234";
    host="super.server.co.uk";
    String passw="12345";
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(passw);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    Channel channel=session.openChannel("shell"); //the power of shell, if i use exec doesn't excecute newgrp...
    //String command = "newgrp xxxx;"; //this doesn't work ...
    //InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8"));
    //channel.setInputStream(is);
    //then somehow printout the response from server...
    channel.setInputStream(System.in); // well instead of this I'd prefer channel.send(command);
    channel.setOutputStream(System.out);
    channel.connect();
    Edited by: 842778 on 14-Mar-2011 01:42

    You seem to be leaving out the newlines.

  • Convert Raw Binary String to InputStream

    Hi i want to upload a {color:#003366}JPG image file{color} in a {color:#003366}BLOB{color} field in database. At first i was using {color:#003366}AJA{color}X to send file {color:#003366}path{color} to the {color:#003366}servlet{color} creating a {color:#003366}file Object{color} from it, then {color:#003366}FileInputStream{color} from it, and finally passing it to {color:#003366}preparedstatement.setBinaryStream({color}) method. It worked great. But since{color:#003366} Firefox 3{color} stopped sending full path to database i have to use another method.
    So instead of sending image path i used {color:#ff0000}nsIDOMFile{color} property of Firefox 3. It has a method {color:#003366}getAsBinary(){color} which Returns a DOMString containing the file's data in {color:#003366}raw binary{color} format. Now i access this {color:#003366}string{color} from servlet using{color:#003366} request.getParameter(){color} method which creates a {color:#003366}String containing bit code of the image file{color} (I suppose). Now how to convert this string to {color:#003366}InputStream{color} so that i can store this in BLOB field in database using prepared statement.
    Right now I am using following code but it doesn't seem to work.
    String image=request.getParameter("image");
        try{
          InitialContext context = new InitialContext();
          dsource = (DataSource)context.lookup("java:comp/env/jdbc/DataSource");
          con = dsource.getConnection();
          ps = con.prepareStatement("SOME STATEMENT");
          ByteArrayInputStream imagestream = new ByteArrayInputStream(image.getBytes());
          ps.setBinaryStream(1, imagestream, imagestream.available());
          int i = ps.executeUpdate();Edited by: Wonder01 on Oct 22, 2008 12:24 PM

    Yeah i came across that too. But these show either iframes hack method (which really isn't ajax) or else writing large pieces of code just to generate the binary stream of the file, then manually creating multipart/form-data request were the only options until Firefox 3 introduced nsIDOMFile. See this and read first few lines (you'll understand what i mean). So i send request in the form of a parameter containing Raw Binary format of the file
    Now going over to the servlet side i need to somehow accept this parameter and insert in database. First i need to know how should i receive this on servlet (By using request.getParameter() or some other method). And secondly, how to convert that to either a byte array or InputStream. I searched for it and think this might be useful. This page shows 1.) how to convert an array of raw binary data into an array of ASCII 0 and 1 characters and 2.) how to convert a String to byte array where each char of the String represents an ASCII '0' or '1'. But what i nedd is slightly different, I need to convert a String containing Raw Binary into byte array.
    And thanks for the information on the file paths. It was really helpful

  • From String to InputStream

    come posso passare da una stringa a un tipo InputStream?
    Grazie

    Making something of a guess at the question:
    Streams work with bytes, not characters. You can convert the string to a byte array and then read the byte array as a InputStream, but you may need to think about how the characters are encoded.
    e.g.
    String theString = ......
    InputStream is = new ByteArrayInputStream(theString.getBytes("UTF-8"));That will encode the characters of the string using UTF-8 and then let you read the resulting bytes.
    Normally if you want to use a String like file input you'd use a StringReader. Readers and Writers, unlike streams, work with characters.

  • String to InputStream. How do I convert it?

    I have a String object, and I want to create an InputStream object out of it. How should I do it? Thanks

    InputStream is = new ByteArrayInputStream(string.getBytes());

  • Webservice returning string (but I need XML for XSLT Tranformation)

    Hello everybody,
    I have configured an ip with a webservice. So far so good - everything works fine.
    Now I want to transform the output of the webservice with xslt. The webservice returns the data as a String in form of XML.
    e.g.
        <!XML>
    <!String>
    <!String> </b>
    </Bill> <!XML>
    But XSLT don't find e.g the node , because it is a String. I think the right way is first to transform the String into XML. I tried this step with Java with the method
    public void execute(InputStream inputStream, OutputStream outputStream)
            throws StreamTransformationException {
    but it doesn't work. I am not sure, if this is the right way.I have searched for a code sample, but I didn't find anything.
    What do you think?
    Do you have a code sample?
    This would be great!
    Best regards,
    Jürgen

    Hello Bhavesh,
    thx very much for your help.
    Here is my Java Mapping:
    public class ModusLebenTransformation implements StreamTransformation
    public static byte[] readStream(InputStream in, boolean close)
        throws IOException
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int c = in.read();
        while (c > -1)
            out.write(c);
            c = in.read();
        out.flush();
        byte[] result = out.toByteArray();
        out.close();
        if (close)
            in.close();
        return result;
    public void setParameter(Map map) {
    public void execute(InputStream inputStream, OutputStream outputStream)
            throws StreamTransformationException {
       try {
    TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer();
       StreamResult result = new StreamResult(outputStream);
    String input = new String(readStream(inputStream,true));
    transformer.transform(new StreamSource(input), result);      
      } catch (Exception e) {
                 throw new StreamTransformationException("Mapping failed", e);
    But I don't know if this code is enough to convert the String( from the webservice) into XML.
    And then I would like to use XSLT for transformation in a new mapping step.
    Do you think this is possible?
    Do you have a code sample, that will tranform the String (from the webservice) into XML?
    This would be very helpful!
    regards,
    Jürgen

  • How use InputStream tt=getServletContext().getResourceAsStream("mf.jasper")

    sir i import all rlated class
    import com.sun.rave.web.ui.appbase.AbstractPageBean;
    import com.sun.rave.web.ui.component.Body;
    import com.sun.rave.web.ui.component.Form;
    import com.sun.rave.web.ui.component.Head;
    import com.sun.rave.web.ui.component.Html;
    import com.sun.rave.web.ui.component.Link;
    import com.sun.rave.web.ui.component.Page;
    import javax.faces.FacesException;
    import com.sun.rave.web.ui.component.Button;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import javax.imageio.*;
    import java.awt.image.*;
    import java.awt.*;
    use this code in button press event
    public String button1_action() {
    InputStream forms = getServletContext().getResourceAsStream("/mfa.jasper");
    return null;
    but sir this line give me error
    i need send jasperviewer to client by streem
    sir how i use streem
    please send me code how i send jasperviewer to client through streem
    thank

    Found the problem. I used DocumentBuilderFactory to create the Source. By default, it is not namespace aware.
    DocumentBuilderFactory.setNamespaceAware(true)does the trick.
    HTH, Markus

  • Unicode to String Conversion

    Dear all,
    I'm trying to get the String from unicode, previously i'm converting the String to Unicode like below,
    String s = "\\u"+Integer.toHexString(s.charAt(0));
    Which is giving me the same what i appended above even after Conversion using UTF-8.
    If i do String s ="\u30f3"
    It is giving me correct character. But my problem is i'm getting the latter part i.e hexString latter in the run time...through Integer.toHexString..
    i can't add this as a character.. so it is taking as a two different strings..
    How to handle this situation..
    Hope i can find the answer,
    Thanks in advance,
    Srinivas N

    Below is my IOUtils class. In particular, see the loadTextFile method for an example of how to read a UTF file, and the isUTF method to detect if a file is Unicode
    You will not be able to compile this class unless you have my InfoFetcher class. You should be able to find a reference to this class by searching google for "InfoFetcher tjacobs01"
    You are welcome to use and modify this class, but please don't change the package or take credit for it as your own work
    package tjacobs.io;
    import java.awt.Component;
    import java.io.*;
    import java.net.URL;
    import java.net.URLConnection;
    import java.text.MessageFormat;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.table.TableModel;
    import tjacobs.io.InfoFetcher.FetcherListener;
    * IOUtils class
    * This is an important class that I use a lot.<p>
    * has a lot of static utilities. Most should be fairly self-explanatory
    public class IOUtils {
         public static final int DEFAULT_BUFFER_SIZE = (int) Math.pow(2, 20); //1 MByte
         public static final int DEFAULT_WAIT_TIME = 30000;
         public static final boolean ALWAYS_BACKUP = false;
         public static String loadTextFile(File f) throws IOException {
              return loadTextFile(f, isUTF16(f));
         public static String loadTextFile(File f, boolean UTF16) throws IOException {
              BufferedReader br = !UTF16 ?
                        new BufferedReader(new FileReader(f)) :
                        new BufferedReader(
                             new InputStreamReader(new FileInputStream(f),
                                                   "UTF-16"));
              int length = (int) f.length();
              char data[] = new char[!UTF16?(int)length : ((int)length) / 2 - 1];
              int got = 0;
              do {
                   got += br.read(data, got, data.length - got);
              while (got < data.length);
              return new String(data);
         public static InfoFetcher loadData(InputStream in) {
              byte buf[] = new byte[DEFAULT_BUFFER_SIZE]; // 1 MByte
              return loadData(in, buf);
         public static InfoFetcher loadData(InputStream in, byte buf[]) {
              return loadData(in, buf, TimeOut.DEFAULT_WAIT_TIME);
         public static InfoFetcher loadData(InputStream in, byte buf[], int waitTime) {
              return new InfoFetcher(in, buf, waitTime);
         public static InfoFetcher loadData(InputStream in, int initBufLength, int waitTime) {
              return loadData(in, new byte[initBufLength], waitTime);
         public static InfoFetcher loadData(File f) throws FileNotFoundException{
              //if (!f.exists()) throw new FileNotFoundException(f.getAbsolutePath());
              //create the inputstream first so that we can generate the FileNotFoundException right away
              InputStream in = new BufferedInputStream(new FileInputStream(f));
              long len = f.length();
              if (len > Integer.MAX_VALUE) {
                   throw new RuntimeException("File size exceeds maximum size for a byte buffer");
              return loadData(in, (int) len, TimeOut.NO_TIMEOUT);
         public static InfoFetcher loadData(URL url) throws IOException{
              return loadData(url.openConnection());
         public static InfoFetcher loadData(URLConnection conn) throws IOException {
              int size = conn.getContentLength();
              if (size < 0) return loadData(conn.getInputStream(), 2000, DEFAULT_WAIT_TIME);
              return loadData(conn.getInputStream(), size, DEFAULT_WAIT_TIME);
          * Note: There is no guarentee that this method will
          * ever return. For instance, if you call loadAll on
          * an open socket connection it won't return until the
          * socket has closed
         public static String loadAllString(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              fetcher.run();
              return new String(fetcher.buf, 0, fetcher.got);
          * Note: There is no guarentee that this method will
          * ever return. For instance, if you call loadAll on
          * an open socket connection it won't return until the
          * socket has closed
         public static byte[] loadAll(InputStream in) {
              InfoFetcher fetcher = loadData(in);
              return fetcher.readCompletely();
         public static void copyBufs(byte src[], byte target[]) {
              int length = Math.min(src.length, target.length);
              for (int i = 0; i < length; i++) {
                   target[i] = src;
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static void pipe (InputStream in, OutputStream out) {
              pipe (in, out, TimeOut.NO_TIMEOUT);
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static void pipe (InputStream in, final OutputStream out, int timeout) {
              pipe (in, out, timeout, false);
         private static class PipeFetcher implements FetcherListener {
              OutputStream out;
              InputStream in;
              public IOException ex;
              boolean closeWhenDone;
              public PipeFetcher (InputStream in, OutputStream out, boolean closeWhenDone) {
                   this.out = out;
                   this.closeWhenDone = closeWhenDone;
              public void fetchedMore(byte[] buf, int start, int end) {
                   try {
                        out.write(buf, start, end - start);
                   catch (IOException iox) {
                        ex = iox;
                        try {
                             in.close();
                             out.close();
                        catch (IOException iox2) {
                             iox2.printStackTrace();
              public void fetchedAll(byte[] buf) {
                   if (closeWhenDone) {
                        try {
                             out.close();
                        catch (IOException iox) {
                             iox.printStackTrace();
         * Not threaded by default. If you need this to run
         * in a separate, create a new thread or runnable class
         * @param in
         * @param out
         public static IOException pipe (final InputStream in, final OutputStream out, int timeout, final boolean closeWhenDone) {
              InfoFetcher info = new InfoFetcher (in, new byte[DEFAULT_BUFFER_SIZE], timeout);
              PipeFetcher pf = new PipeFetcher(in, out, closeWhenDone);
              info.addFetcherListener(pf);
              info.run();
              return pf.ex;
              info.addInputStreamListener(new InputStreamListener() {
                   public void gotMore(InputStreamEvent ev) {
                        try {
                             out.write(ev.getBytes(), ev.getStart(), ev.getBytesRetrieved() - ev.getStart());
                        catch (IOException iox) {
                             System.err.println ("Pipe closing");
                   public void gotAll(InputStreamEvent ev) {}
              Thread t= new Thread (info);
              t.start();
         public static byte[] expandBuf(byte array[]) {
              return expandBuf(array, array.length * 2);
         public static byte[] expandBuf(byte array[], int newlength) {
              byte newbuf[] = new byte[newlength];
              copyBufs(array, newbuf);
              return newbuf;
         public static byte[] trimBuf(byte[] array, int size) {
              byte[] newbuf = new byte[size];
              for (int i = 0; i < size; i++) {
                   newbuf[i] = array[i];
              return newbuf;
         * @see getFileOutputStream(File, boolean)
         public static OutputStream getFileOutputStream(File file) throws IOException {
              return getFileOutputStream(file, true);
         * Convienience method for opening a FileOutputStream w/wo a buffer
         * makes sure that the file directory exists so this should always succeed.
         public static OutputStream getFileOutputStream(File file, boolean buffered) throws IOException {
              if (!file.exists() && !file.isDirectory()) {
                   confirmDirectoryExists(file.getParentFile());
              if (file.exists()) {
                   if (ALWAYS_BACKUP) {
                        file.renameTo(new File(file.getAbsolutePath() + "~"));
                   } else {
                        file.delete();
              file.createNewFile();
              OutputStream out = new FileOutputStream(file);
              if (buffered) {
                   out = new BufferedOutputStream(out);
              return out;
         * Confirms that a directory exists and makes it if it doesn't
         public static void confirmDirectoryExists(File dir) {
              if (!dir.exists()) {
                   confirmDirectoryExists(dir.getParentFile());
                   dir.mkdir();
              if (!dir.isDirectory()) {
                   confirmDirectoryExists(dir.getParentFile());
         public static OutputStream getFileOutputStream(String name) throws IOException {
              return getFileOutputStream(name, true);
         public static PrintStream getFilePrintStream(String file) throws IOException {
              return new PrintStream(getFileOutputStream(file));
         public static PrintStream getFilePrintStream(File file) throws IOException {
              return new PrintStream(getFileOutputStream(file));
         public static OutputStream getFileOutputStream(String name, boolean buffered) throws IOException {
              return getFileOutputStream(new File(name), buffered);
         * @param f if f is a directory it returns the absolue path to f otherwise it returns the absolute path to the directory f is in
         public static String getDirectory(File f) {
              if (f.isDirectory()) {
                   return f.getAbsolutePath();
              else {
                   return f.getParentFile().getAbsolutePath();
         * Get the file without the extension.
         * @see getFileNoExtension(String);
         public static String getFilenameNoExtension(File f) {
              return getFilenameNoExtension(f.getName());
         * Gets the file name without the extension
         * returns the whole file name if no '.' is found<br>
         * otherwise returns whatever's before the last .
         public static String getFilenameNoExtension(String s) {
              int idx = s.indexOf('.');
              if (idx == -1) {
                   return s;
              else {
                   return s.substring(0, idx);
         * gets the file extension
         * if a '.' character is found it returns what's after the last .
         * if not, it returns the empty string
         public static String getFileExtension(String s) {
              int idx = s.lastIndexOf('.');
              if (idx == -1) {
                   return "";
              else {
                   return s.substring(idx + 1);
         * @see getFileExtension(String)
         public static String getFileExtension(File f) {
              return getFileExtension(f.getName());
         * Delete everything in a directory. Recursively deletes all sub-directories
         public static void deleteDirectory (File f, Component parent) {
              if (!f.isDirectory()) {
                   throw new RuntimeException("File " + f.getAbsolutePath() + " is not a directory!");
              int val = JOptionPane.showConfirmDialog(parent, "Confirm Delete " + f.getAbsolutePath(), "Confirm Delete " + f.getAbsolutePath(), JOptionPane.OK_CANCEL_OPTION);
              if (val == JOptionPane.OK_OPTION) {
                   deleteAllFiles(f);
         private static void deleteAllFiles (File f) {
              //recursively delete all its contents
              if (!f.isDirectory()) {
                   //throw new RuntimeException("File " + f.getAbsolutePath() + " is not a directory!");
                   f.delete();
              else {
                   File[] files = f.listFiles();
                   for (int i = 0; i < files.length; i++) {
                        if (files[i].equals(f) || files[i].equals(f.getParent())) {
                             continue;
                        deleteAllFiles(files[i]);
                   f.delete();
         * static utility method for copying a file to another location
         public static void copyFile (File src, File newParent) throws FileNotFoundException {
              if (!src.exists()) {
                   return;
              if (!newParent.exists()) {
                   newParent.mkdirs();
                   //throw new RuntimeException("Parent folder must exist");
              if (newParent.isDirectory()) {
                   File newFile = new File(newParent, src.getName());
                   if (src.isDirectory()) {
                        newFile.mkdir();
                        File children[] = src.listFiles();
                        for (int i = 0; i < children.length; i++) {
                             copyFile(children[i], newFile);
                   else {
                        //loadFile
                        InfoFetcher info = loadData(new FileInputStream(src));
                        final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile));
                        info.addInputStreamListener(new InputStreamListener() {
                             int lastbytes = 0;
                             public void gotMore(InputStreamEvent ev1) {
                                  try {
                                       out.write(ev1.getBytes(), lastbytes, ev1.getBytesRetrieved() - lastbytes);
                                       lastbytes = ev1.getBytesRetrieved();
                                  catch (IOException iox) {
                                       iox.printStackTrace();
                             public void gotAll(InputStreamEvent ev2) {
         * @deprecated use the Find class
         public static File find(Pattern p, File start) {
              return recursiveFind(start, null, p, true);
         * @deprecated use the Find class
         public static File find(Pattern p) {
              return find(p, new File("."));
         * @deprecated use the Find class
         private static File recursiveFind(File current, File cameFrom, Pattern p, boolean startDescending) {
              Matcher m = p.matcher(current.getName());
              if (m.matches()) {
                   return current;
              File[] files = current.listFiles();
              if (startDescending) {
                   File value = descend(current, cameFrom, p, startDescending);
                   if (value != null) return value;
                   return ascend(current, cameFrom, p, startDescending);
              else {
                   File value = ascend(current, cameFrom, p, startDescending);
                   if (value != null) return value;
                   return descend(current, cameFrom, p, startDescending);               
         * @deprecated use the Find class
         private static File ascend(File current, File cameFrom, Pattern p, boolean startDescending) {
              File par = current.getParentFile();
              if (par == null) {
                   return null;
              par = par.getAbsoluteFile();
              if (par.equals(cameFrom)) {
                   return null;
              return recursiveFind(par, current, p, false);
         * @deprecated use the Find class
         private static File descend(File current, File cameFrom, Pattern p, boolean startDescending) {
              File files[] = current.listFiles();
              if (files == null) {
                   return null;
              for (int i = 0; i < files.length; i++) {
                   File child = files[i];
                   if (child.equals(cameFrom)) {
                        continue;
                   File f = recursiveFind(child, current, p, true);
                   if (f != null) {
                        return f;
              return null;
         * Utility for saving a string to a file. Rather than have to set
         * up all the writers etc and trap exceptions, just returns a boolean
         * if it worked
         * <p>
         * @see saveData(File, byte[])
         public static boolean saveData(File f, String s) {
              return saveData(f, s.getBytes());
         * Utility for saving a string to a file. Rather than have to set
         * up all the writers etc and trap exceptions, just returns a boolean
         * if it worked
         public static boolean saveData(File f, byte[] data) {
              try {
                   OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
                   out.write(data);
                   out.close();
              catch(IOException iox) {
                   iox.printStackTrace();
                   return false;
              return true;
         * Way to save a stream to a file. Not multithreaded.
         * Will block until the save is done
         * @param f
         * @param in
         * @return
         public static boolean saveData(File f, InputStream in) throws FileNotFoundException {
              return pipe(in, new FileOutputStream(f), TimeOut.NO_TIMEOUT, true) == null;
              //InfoFetcher fetcher = loadData(in);
    //          try {
    //               FileOutputStream out = new FileOutputStream(f);
    //               fetcher.addFetcherListener(new FetcherListener() {
    //                    public void fetchedMore(byte[] buf, int start, int end) {
    //                    public void fetchedAll(byte[] buf) {
    //          } catch (IOException iox) {
    //               iox.printStackTrace();
    //               return false;
    //          return true;
         * @deprecated use Find
         public static List<File> findAllFiles(Pattern p) {
              ArrayList<File> l = new ArrayList<File>();
              //File start = File.listRoots()[0];
              File start = new File("C:\\");
              return recursiveFindAll(start, null, p, true, l, 0);
              //l;
         * @deprecated use Find
         private static List recursiveFindAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              //System.out.println("" + level + " Scanning: " + current + "par: " + cameFrom);
              System.out.println("Scanning: " + current);
              Matcher m = p.matcher(current.getName());
              if (current.getName().equals("C:\\")) {
                   System.out.println("root");
                   try {
                        System.in.read();
                   catch (IOException iox) {}
              if (m.matches()) {
                   //return current;
                   list.add(current);
                   System.out.println("Adding " + current);
              File[] files = current.listFiles();
              if (startDescending) {
                   //File value = descend(current, cameFrom, p, startDescending);
                   descendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //ascendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //if (value != null) return value;
                   //return ascend(current, cameFrom, p, startDescending);
              else {
                   //ascendAll(current, cameFrom, p, startDescending, list, level + 1);
                   descendAll(current, cameFrom, p, startDescending, list, level + 1);
                   //File value = ascend(current, cameFrom, p, startDescending);
                   //if (value != null) return value;
                   //return descend(current, cameFrom, p, startDescending);               
              return list;
         * @deprecated use Find
         private static List ascendAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              File par = current.getParentFile();
              if (par == null) {
                   return list;
              par = par.getAbsoluteFile();
              if (par.equals(cameFrom)) {
                   return list;
              recursiveFindAll(par, current, p, false, list, level);
              return list;
         * @deprecated use Find
         private static File descendAll(File current, File cameFrom, Pattern p, boolean startDescending, ArrayList<File> list, int level) {
              File files[] = current.listFiles();
              if (files == null) {
                   return null;
              for (int i = 0; i < files.length; i++) {
                   File child = files[i];
                   if (child.equals(cameFrom)) {
                        continue;
                   recursiveFindAll(child, current, p, true, list, level);
              return null;
         public File getUniqueName(File f) {
              return getUniqueName (f, new MessageFormat("~{0,number,integer}"));
         public String getNameWOExtension(File f, boolean useAbsolute) {
              int idx = f.getName().indexOf(".");
              return (idx == -1) ? (useAbsolute ? f.getAbsolutePath() : f.getName()) : (useAbsolute ? f.getAbsolutePath() : f.getName()).substring(0, (useAbsolute ? f.getAbsolutePath().lastIndexOf(".") : f.getName().lastIndexOf(".")));
         public String getFileType (File f, boolean includeDot) {
              int idx = f.getName().lastIndexOf(".");
              return idx == -1 ? "" : f.getName().substring(idx + (includeDot ? 0 : 1));
         public File getUniqueName(File f, MessageFormat format) {
              String base = getNameWOExtension(f, true);
              String extension = getFileType(f, true);
              int count = 0;
              while (f.exists()) {
                   count++;
                   f = new File (base + format.format(new Object[] {Integer.valueOf(count)}) + extension);
              return f;
         public static boolean isUTF16 (File f) throws IOException {
              FileInputStream in = null;
              try {
                   if (!f.exists() || f.length() < 2) return false;
                   in = new FileInputStream(f);
                   byte b = (byte)in.read();
                   if (!(b == -1)) return false;
                   b = (byte) in.read();
                   return b == -2;
              finally {
                   if (in != null) in.close();
         public static boolean isUTF16(PushbackInputStream in) {
              boolean got1 = false, got2 = false;
              byte b = 0, b2 = 0;
              try {
                   b = (byte)in.read();
                   got1 = true;
                   if (!(b == -1 || b== -2)) {
                        return false;
                   b2 = (byte) in.read();
                   got2 = true;
                   return b == -1 ? b2 == -2 : b2 == -1;
              catch (IOException iox) {
                   iox.printStackTrace();
              finally {
                   try {
                        if (got1) {
                             in.unread(b);
                        if (got2) {
                             in.unread(b2);
                   } catch (IOException iox) {
                        iox.printStackTrace();
              return false;
         public void saveJTableToCSV(JTable table, File f) throws IOException {
              if (table == null || f == null) return;
              TableModel model = table.getModel();
              if (model == null) return;
              int rows = model.getRowCount();
              int columns = model.getColumnCount();
              PrintWriter pw = new PrintWriter(new FileWriter(f));
              for (int i = 0; i < rows; i++) {
                   for (int j = 0; j < columns; j++) {
                        Object o = model.getValueAt(i, j);
                        pw.print(o.toString());
                        if (j != columns - 1) {
                             pw.print(",");
                   pw.println();
         public static String getPathRelativeTo(File path, File relativeTo) {
              return getPathRelativeTo(path.getAbsolutePath(), relativeTo.getAbsolutePath());
         public static String getPathRelativeTo(String path, String relativeTo) {
              if (!path.startsWith(relativeTo)) return null;
              path = path.substring(relativeTo.length());
              if (path.startsWith(File.separator)) path = path.substring(File.separator.length());
              return path;

  • Finding strings in a text file?

    Hi! i'm learning to read text files. what i want to do with this program is to find word 1-3, 2-4, 3-5... and write them in a system.out.println. i found a program that opens files and count words, lines and characters and tried to adjust it do find three-word strings.
    i can compilate (hope that word exists) but when i run it, it says: Exception in thread "main" java.lang.NoSuchMethodError: main
    anyone who knows what this could depend on?
    This is what the code looks like:
    import java.io.*;
    import java.io.*;
    import java.util.*; //tillagd f�r att removeFirst4 skall funka
    import javax.swing.*; //tillagd f�r att removeFirst4 skall fungera
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    import java.lang.*;
    import javax.swing.*;
    public class AttLaesaEnFil2 {
         private static void samla(String name, BufferedReader in) throws
         IOException {
         String a;
         WordExtractor b;
    String c = " ";
    String d;
    WordExtractor e;
    String f;
    String g;
    WordExtractor h;
    String i;
    String j;
    String k;
    String l;
    String line;
    do {
                   line = in.readLine();
                   if (line != null)
    b = new WordExtractor(line);
         c = b.getFirst();
         d = b.getRest();
         e = new WordExtractor(d);
         f = e.getFirst();
         g = e.getRest();
         h = new WordExtractor(g);
         i = h.getFirst();
         j = h.getRest();
         k = c + f + i;
         l = c + " " + f + " " + i;
         System.out.println("The first three words are: " + l);
         a = b.getRest();
    while (line != null);
              System.out.println("Klart!");
              private static void samla(String fileName) {
              BufferedReader in = null;
              try {
                   FileReader fileReader = new FileReader(fileName);
                   in = new BufferedReader(fileReader);
                   samla(fileName, in);
              } catch (IOException ioe) {
                   ioe.printStackTrace();
              } finally {
                   if (in != null) {
                        try {
                             in.close();
                        } catch (IOException ioe) {
                             ioe.printStackTrace();
         private static void samla(String streamName, InputStream input) {
              try {
                   InputStreamReader inputStreamReader = new InputStreamReader(input);
                   BufferedReader in = new BufferedReader(inputStreamReader);
                   samla(streamName, in);
                   in.close();
              } catch (IOException ioe) {
                   ioe.printStackTrace();
    Thanx in advance!

    this may be a stupid question but i'll give it a
    shot. ...do i replace my private static void with
    public static void or do a add the public?Whether you replace one of your methods or create a new one is up to you, but you have to have a method with this exact signature:
    public static void main(String[] foo) {
    }(The variable name can be different of course)

  • JAXB: Read XML data from a String?

    Hi,
    I get XML data not from file but as a string and I wanted to use JAXB to parse it and get my Java Objects.
    The unmarshall methods wants an "InputStream", but "StringBufferInputStream" is deprecated, so that I don't know a way to use my String as InputStream.
    Can someone give me a hint other then writing the data in a file first?

    Hi FrankSch,
    The unmarshall methods wants an "InputStream", but
    "StringBufferInputStream" is deprecated, so that I
    don't know a way to use my String as InputStream.
    Can someone give me a hint other then writing the data
    in a file first?Yes, the class StringBufferInputStream is deprecated, and the deprecation notice reads:
    Deprecated. This class does not properly convert characters into bytes. As of JDK 1.1, the preferred way to create a stream from a string is via the StringReader class.
    The JDK API usually mentions an alternative to the deprecated method/class and in this case, you should use java.io.StringReader. It has one constructor and should suite you nicely:
    StringReader(String s) That way, you get an InputStream object; you can now use JAXB.
    Hope this helps,
    -ike, .si

  • Printing the string

    The below code is print the data in the cheque.For this i create a template and replace in the template with data.
    StringBuffer checkTemplate = new StringBuffer();
    checkTemplate.append(" VENDOR_NUMBER______ VENDOR_NAME________________________ CHECK_DATE\n");
    checkTemplate.append(" \n");
    checkTemplate.append(" REF_NUMBER_A INVDATE_A GROSS_AMOUNT_A DISC_TAKEN_A NET_AMT_PAID_A\n");
    I replace this with my data later and place it in a string
    and this string is passed as a parameter to the below function.
    void printIt(String printString) {
    InputStream textStream = new ByteArrayInputStream(printString.getBytes());
    DocFlavor myFormat=DocFlavor.INPUT_STREAM.AUTOSENSE ;
    Doc myDoc = new SimpleDoc(textStream, myFormat, null);
    if (printJob.printDialog()){
    try {
    printService=printJob.getPrintService();
    printJob.setPrintService(printService);
    job = printService.createPrintJob();
    PrintJobWatcher pjw = new PrintJobWatcher(job);
    job.print(myDoc, aset);
    pjw.waitForDone();
    print = true;
    }catch(Exception pe){
    pe.printStackTrace();
    My problem is when i send this string to the laser printer, The string contains the line character "\n" .Even though it contains the new line character laser printer doesnot print line by line. it prints all the string at one line
    Please help me.
    Edited by: 889575 on Oct 5, 2011 2:41 AM
    Edited by: 889575 on Oct 5, 2011 2:44 AM
    Edited by: 889575 on Oct 6, 2011 4:11 AM
    Edited by: 889575 on Oct 6, 2011 10:42 AM

    When posting code, 1) Use code tags: https://forums.oracle.com/forums/ann.jspa?annID=1429 and 2) Provide an [url http://sscce.org]SSCCE that only shows the relevant code and nothing else. For instance, do you think we really need to see all those append() lines? No. Two or three would suffice. And in fact, that's how you should have been testing in the first place. Don't start by testing everything. Start by testing just a tiny piece, and only add more when that piece works.

  • Arraylist.add() problem

    Hi,
    I'm trying to read a CSV text file into an arraylist.
    I can read the text file fine, its just when it gets to the actual arraylist.add() part it just .. .. doesn't work. It can print the values from the CSV file no problem. I'm sure my syntax is fine, everything compiles. I've read it and double checked it and checked it again.
    It just doesn't work .. I don't know why.
    The arraylist I am trying to read into is
    ArrayList<Customer> customers = new ArrayList<Customer>();Within other parts of the program I can read in dummy data, eg
    customers.add(new Customer(01, "Jims Mowing", "16 Long Grass Street", "Thorndale", "123-4567", "[email protected]"));
    but suffice to say, yes, it is kaput.
       * READING THE CUSTOMER TEXT FILE INTO THE ARRAY LIST
      private void custFileToArray ()
        RectangleTUI results = new RectangleTUI(); // create results object
        try   
          BufferedReader inputStream = new BufferedReader(new FileReader(PATHNAME + CUSTFILE));
          System.out.println("Contents of file: " + CUSTFILE); // print heading
          String line = inputStream.readLine(); // read first line
          while (line !=null) // test for end of file (EOF)
            results.loadCustFile(line);       
            line = inputStream.readLine(); // read next line
          // close file
          inputStream.close();
        // catch any file open errors
        catch(FileNotFoundException e)
          System.out.println("Error opening file: " + CUSTFILE);
          System.exit(0);
        catch(NoSuchElementException e)
          System.out.println("ATTENTION: One or more " + CUSTFILE + " records are missing data");
        // catch any file reading errors
        catch(IOException e)
          System.out.println("Error reading from file: " + CUSTFILE);
          System.exit(0);
        System.out.println("File Reading Complete");  
      private void loadCustFile(String textLine)
        String delimiters = ","; // set tokenizer delimiter
        StringTokenizer RecordFields = new StringTokenizer(textLine,delimiters);  
        int cidNum = Integer.parseInt(RecordFields.nextToken()); // Customer ID
        System.out.println(cidNum + " Hello I am a stupid piece of code. I don't like to work properly");
        String cName = RecordFields.nextToken();   // Name
        String cAdd = RecordFields.nextToken();   // Street Address
        String cBurb = RecordFields.nextToken();   // Suburb
        String cPhone = RecordFields.nextToken();   // Phone
        String cEmail = RecordFields.nextToken();   // Email
        customers.add(new Customer(cidNum, cName, cAdd, cBurb, cPhone, cEmail));
      }

    Cowzor wrote:
    Hi,
    Cheers for the replies & the printStackTrace tip.
    The thing is it's not actually throwing up any errors or crashing. It's acting as if everything is AOK - but since it then says there's nothig in the arraylist there must be a problem ... somewhere.
    Sorry if I've mis-understood what you were saying
    Here's the dummy data I'm using just incase it's at all relevant
    200701,Jims Mowing,16 Long Grass Street,Thorndale,123-4567,[email protected]
    200702,Chevy Racers,2 Raceway Drive,Boganville,123-4567,[email protected]
    200703,Renta Dent,82 Airport Oaks Road,Airport Oaks,123-4567,[email protected]
    200704,Discount Taxis,8 Poor Place,Otara,123-4567,[email protected]
    u split contains of CSV file on basis of , (comma) and read it

  • SOAP Reponse contains &gt and &lt instead of and

    I am new to Web Services. I wrote a simple SOAP client in Java. It seems to work and I get the SOAP response back; however the XML response has < and > instead of < and >. Am I making a mistake in my source code? I have placed my source code below and the result that I get when I run the code. How do I get a proper response with < and > instead of &lt and &gt?
    Webservice Endpoint: http://www.webservicex.net/stockquote.asmx
    WSDL Location: http://www.webservicex.net/stockquote.asmx?wsdl
    From the <GetQuoteResult>, the reponse I get has &lt and &gt for < and >. However, when I past it here, the &lt and &gt are being converted to < and >.
    SOAP Response that I get:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.
    xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    " xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmln
    s="http://www.webserviceX.NET/"><GetQuoteResult><StockQuotes><Stock>
    <Symbol>IBN</Symbol><Last>38.58</Last><Date>7/30/2
    010</Date><Time>10:24am</Time><Change>-0.35</Change&g
    t;<Open>38.42</Open><High>38.86</High><Low>38.29&l
    t;/Low><Volume>314170</Volume><MktCap>21.505B</MktCap&gt
    ;<PreviousClose>38.93</PreviousClose><PercentageChange>-0.90%&
    lt;/PercentageChange><AnnRange>28.53 - 45.95</AnnRange><Earns&
    gt;1.782</Earns><P-E>21.85</P-E><Name>ICICI Bank Limite&
    lt;/Name></Stock></StockQuotes></GetQuoteResult></GetQuoteRespons
    e></soap:Body></soap:Envelope>
    SOAP response that I am expecting:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.
    xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    " xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmln
    s="http://www.webserviceX.NET/"><GetQuoteResult><StockQuotes><Stock>
    <Symbol>IBN</Symbol><Last>38.58</Last><Date>7/30/2
    010</Date><Time>10:24am</Time><Change>-0.35</Change&g
    t;<Open>38.42</Open><High>38.86</High><Low>38.29&l
    t;/Low><Volume>314170</Volume><MktCap>21.505B</MktCap&gt
    ;<PreviousClose>38.93</PreviousClose><PercentageChange>-0.90%&
    lt;/PercentageChange><AnnRange>28.53 - 45.95</AnnRange><Earns&
    gt;1.782</Earns><P-E>21.85</P-E><Name>ICICI Bank Limite&
    lt;/Name></Stock></StockQuotes></GetQuoteResult></GetQuoteRespons
    e></soap:Body></soap:Envelope>
    Source Code:
    import java.net.*;
    import java.io.*;
    public class stocksoapClient {
      public final static String DEFAULT_SERVER = "http://www.webservicex.net/stockquote.asmx";
      public final static String SOAP_ACTION = "http://www.webserviceX.NET/GetQuote";
      public static void main(String[] args) {
        String input = "IBN";
        String server = DEFAULT_SERVER;
        if (args.length >= 2) server = args[1];
        try {
               Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.compaq.com", 8080));        
               URL u = new URL(server);
               URLConnection uc = u.openConnection(proxy);
               HttpURLConnection connection = (HttpURLConnection) uc;
               connection.setDoOutput(true);
               connection.setDoInput(true);
               connection.setRequestMethod("POST");
               connection.setRequestProperty("Content-Type",  "text/xml; charset=utf-8");
               connection.setRequestProperty("Content-Length",  String.valueOf(input.length()));
               connection.setRequestProperty("SOAPAction", SOAP_ACTION);
               //connection.connect();
               OutputStream out = connection.getOutputStream();
               Writer wout = new OutputStreamWriter(out);
               //wout.write("POST" + DEFAULT_SERVER  + "HTTP/1.1");
               //wout.write("Host:www.webservicex.net");
               //wout.write("Content-Type: text/xml; charset=utf-8");
               //wout.write("Content-Length: " + String.valueOf(input.length()));
               //wout.write("SOAPAction:" + SOAP_ACTION);         
              //wout.write("\n");     
               wout.write("<?xml version='1.0' encoding='utf-8'?>"); 
               wout.write("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
               wout.write("<soap:Body>");
               wout.write("<GetQuote xmlns='http://www.webserviceX.NET/'>");
               wout.write("<symbol>"+input+"</symbol>");
               wout.write("</GetQuote>");     
               wout.write("</soap:Body>");
               wout.write("</soap:Envelope>");
               wout.flush();
               wout.close();
               BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
               String line;     
               //InputStream in = connection.getInputStream();
               //int c;
               while ((line=rd.readLine()) != null) {
                  System.out.println(line);
               rd.close();
        } catch (IOException e) {
               System.err.println(e);
    }

    This problem won't occur if the server side returns xmlobject to the client instead of a xmlstring
    Thanks
    Srinivas K G

  • SOAP Reponse contains and instead of and

    I am new to Web Services. I wrote a simple SOAP client in Java. It seems to work and I get the SOAP response back; however the XML response has < and > instead of < and >. Am I making a mistake in my source code? I have placed my source code below and the result that I get when I run the code.
    Webservice Endpoint: http://www.webservicex.net/stockquote.asmx
    WSDL Location: http://www.webservicex.net/stockquote.asmx?wsdl
    SOAP Response that I get:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.
    xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    " xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmln
    s="http://www.webserviceX.NET/"><GetQuoteResult><StockQuotes><Stock>
    <Symbol>IBN</Symbol><Last>38.58</Last><Date>7/30/2
    010</Date><Time>10:24am</Time><Change>-0.35</Change&g
    t;<Open>38.42</Open><High>38.86</High><Low>38.29&l
    t;/Low><Volume>314170</Volume><MktCap>21.505B</MktCap&gt
    ;<PreviousClose>38.93</PreviousClose><PercentageChange>-0.90%&
    lt;/PercentageChange><AnnRange>28.53 - 45.95</AnnRange><Earns&
    gt;1.782</Earns><P-E>21.85</P-E><Name>ICICI Bank Limite&
    lt;/Name></Stock></StockQuotes></GetQuoteResult></GetQuoteRespons
    e></soap:Body></soap:Envelope>
    SOAP response that I am expecting:
    <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.
    xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
    " xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetQuoteResponse xmln
    s="http://www.webserviceX.NET/"><GetQuoteResult><StockQuotes><Stock>
    <Symbol>IBN</Symbol><Last>38.58</Last><Date>7/30/2
    010</Date><Time>10:24am</Time><Change>-0.35</Change&g
    t;<Open>38.42</Open><High>38.86</High><Low>38.29&l
    t;/Low><Volume>314170</Volume><MktCap>21.505B</MktCap&gt
    ;<PreviousClose>38.93</PreviousClose><PercentageChange>-0.90%&
    lt;/PercentageChange><AnnRange>28.53 - 45.95</AnnRange><Earns&
    gt;1.782</Earns><P-E>21.85</P-E><Name>ICICI Bank Limite&
    lt;/Name></Stock></StockQuotes></GetQuoteResult></GetQuoteRespons
    e></soap:Body></soap:Envelope>
    Source Code:
    import java.net.*;
    import java.io.*;
    public class stocksoapClient {
      public final static String DEFAULT_SERVER = "http://www.webservicex.net/stockquote.asmx";
      public final static String SOAP_ACTION = "http://www.webserviceX.NET/GetQuote";
      public static void main(String[] args) {
        String input = "IBN";
        String server = DEFAULT_SERVER;
        if (args.length >= 2) server = args[1];
        try {
               Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.compaq.com", 8080));        
               URL u = new URL(server);
               URLConnection uc = u.openConnection(proxy);
               HttpURLConnection connection = (HttpURLConnection) uc;
               connection.setDoOutput(true);
               connection.setDoInput(true);
               connection.setRequestMethod("POST");
               connection.setRequestProperty("Content-Type",  "text/xml; charset=utf-8");
               connection.setRequestProperty("Content-Length",  String.valueOf(input.length()));
               connection.setRequestProperty("SOAPAction", SOAP_ACTION);
               //connection.connect();
               OutputStream out = connection.getOutputStream();
               Writer wout = new OutputStreamWriter(out);
               //wout.write("POST" + DEFAULT_SERVER  + "HTTP/1.1");
               //wout.write("Host:www.webservicex.net");
               //wout.write("Content-Type: text/xml; charset=utf-8");
               //wout.write("Content-Length: " + String.valueOf(input.length()));
               //wout.write("SOAPAction:" + SOAP_ACTION);         
              //wout.write("\n");     
               wout.write("<?xml version='1.0' encoding='utf-8'?>"); 
               wout.write("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
               wout.write("<soap:Body>");
               wout.write("<GetQuote xmlns='http://www.webserviceX.NET/'>");
               wout.write("<symbol>"+input+"</symbol>");
               wout.write("</GetQuote>");     
               wout.write("</soap:Body>");
               wout.write("</soap:Envelope>");
               wout.flush();
               wout.close();
               BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
               String line;     
               //InputStream in = connection.getInputStream();
               //int c;
               while ((line=rd.readLine()) != null) {
                  System.out.println(line);
               rd.close();
        } catch (IOException e) {
               System.err.println(e);
    }

    I meant to say my SOAP response contains "&lt" and "&gt" instead of < and >.
    Edited by: [email protected] on Jul 30, 2010 7:44 AM
    Edited by: [email protected] on Jul 30, 2010 7:44 AM

  • Help on ftpClient

    Hi there,
    I am a Oracle Developer and I would request your help in using ftpClient. I am using following code for ftping files and then deleting them from the ftp server.
    import java.io.*;
    import oracle.sql.*;
    import java.io.IOException;
    import sun.net.TransferProtocolClient;
    import sun.net.ftp.FtpClient;
    import java.util.Enumeration;
    import java.util.Vector;
    import FullFtpClient;
    public class ORIX_ftp
    public static int fget
    String host, //FTP server ip address or name
    NUMBER port, //FTP server ftp port number
    String username, //FTP server username
    String password, //FTP server password
    String transtype, //FTP transfer type "ASCII" or "BINARY"
    String remotedir, //Remote or FTP server directory path from where files will be fetched
    String localdir, //Local or Oracle server directory path where files will be fetched
    String filenames, //File names seperated by on Remote or FTP server to be fetched from the
    String deletefile, //Delete file after file transfer from FTP Server to Database Server
    String ErrorMessage[]
    FullFtpClient FullFtpClient = new FullFtpClient();
    int ErrorStatus = 0;
    try
    FullFtpClient = new FullFtpClient(host, port.intValue()); //Making FTP connection
    FullFtpClient.login(username, password); //Logging on to FTP server
    if (transtype == "ASCII")
    FullFtpClient.ascii(); //Setting FTP transfer to ascii mode
    if (transtype == "BINARY")
    FullFtpClient.binary(); //Setting FTP transfer to binary mode
    //ftpClient.cd(remotedir); //Set remote or FTP server directory
    if (null != filenames)
    int StartIndex = 0, PosIndex = 0;
    String fname;
    InputStream is;
    int length;
    byte[] buffer;
    File file_out;
    OutputStream os;
    while (-1 != (PosIndex = filenames.indexOf("///",StartIndex)))
    //For each filename the file will be fetched
    fname = filenames.substring(StartIndex,PosIndex);
    is = FullFtpClient.get(fname);
    length = 1;
    buffer = new byte[1024];
    file_out = new File(localdir + "\\" + fname);
    os = new FileOutputStream (file_out);
    while((length = is.read(buffer)) != -1)
    os.write(buffer, 0, length);
    PosIndex += 3;
    StartIndex = PosIndex;
    if (deletefile != null)
    FullFtpClient.delete (fname); // Remove file from FTP server
    // Last, or only, filename;
    if (StartIndex < filenames.length())
    fname = filenames.substring(StartIndex);
    is = FullFtpClient.get(fname);
    length = 1;
    buffer = new byte[1024];
    file_out= new File(localdir + "\\" + fname);
    os = new FileOutputStream (file_out);
    while((length = is.read(buffer)) != -1)
    os.write(buffer, 0, length);
    if (deletefile != null)
    FullFtpClient.delete (fname); // Remove file from FTP server
    if (FullFtpClient != null)
    // FullFtpClient.delete (filenames);
    FullFtpClient.closeServer(); //Closing the FTP connection
    catch (Exception e)
    ErrorMessage[0] = e.toString();
    ErrorStatus = 1;
    return ErrorStatus;
    Although I am catching the Exception, I get exceptions such as NullPointerException and Dele command could not delete file because access denied.
    What I want is to transfer the file from ftp server and then delete it only after the transfer is complete. Secondly I want to handle any exception whatsoever arises during the execution of this code.
    You help will be of gr8 help.
    Thanx a lot
    Alok

    That is because I don't want to pile the files on the ftp server. Actually the file is transferred from ftp server on to the oracle server, then using javamail its sent to the user and after that there is no point keeping that file on the server. So I want to delete it from both the servers. I am able to delete the file from oracle server but I am unable to delete it from ftp server. Your help would be greatly appreciated.
    Thanks & regards,
    Alok

Maybe you are looking for