GetResourceAsStream(String name)  - how to use it?

I tryed to read from a "res.txt" file some text data. This is a test app:
public class ResTest extends MIDlet{
     public void startApp(){
          try{
               InputStream is=new String().getClass().getResourceAsStream("/res.txt");
               DataInputStream dis=new DataInputStream(is);
               System.out.println(dis.readUTF());
          }catch(Exception e){System.out.println(e);}     
     public void destroyApp(boolean bool){}
     public void pauseApp(){}
All I got was EOFException.
So I tryed a different way to read data usinf a loop:
               char ch;
               while((ch=dis.readChar())!=-1){
               System.out.print(ch);
And than I got:
??????java.io.EOFException
The data in "res.txt" file (I put this file to "res" direction of my project, I use KToolbar):
Jajko
Banan

I'm guessing that the res.txt file is a basic ASCII file, right?
If this is the case then that is your problem. When you used readUTF() the implementation was expecting a string in UTF format and not basic ASCII so it didn't know how to read it.
And when you used the readChar() method you have to remember that Java is a Unicode language so chars are 2 bytes. If the string has an odd number of characters then the last character won't have the 2 bytes and you will get an EOFException. And even if the number of chars was even, you wouldn't get the exception but the text wouldn't be what you expect since it was reading text encoded in single byte ASCII format.
You have two choices:
a) Encode the res.txt file appropiately, either save as as a UTF-8 file and use readUTF(), or a Unicode file and use the readChar() method.
b) Use readByte() instead of readChar() and save the bytes in an array, then pass that array to a string constructor.
shmoove

Similar Messages

  • String contains class name: how to use it for creating new objects

    Hi All
    I've seen things like this in scripting languages, so I was wondering if things like this are possible in java. Here is an not working example:
    String s = "MyClass" ;
    MyClass mc = new s() ; // or: s mc = new s() ;
    if ( mc instanceof s ) { ..... }
    Is something like this possible ?
    Thnx in advance
    LuCa

    jeanluca wrote:
    I've seen things like this in scripting languages, so I was wondering if things like this are possible in java. Here is an not working example:
    Is something like this possible ?AFAIK, it is only possible in a very limited way as noted above and is nearly always not recommended and definitely not necessary. The variable name has little importance, but OTOH the object reference has great importance. Instead learn about arrays, Lists, and Maps.

  • JobAttributes.setPrinter(String printer) How to use it?

    Anynody knows whether setPrinter(...) method can change the default printer? I'm using win2k and here is my code:
    JobAttributes ja=new JobAttributes();
    ja.setDestination(JobAttributes.DestinationType.PRINTER);
    ja.setPrinter("HP LaserJet 2100"); //<<<<
    ja.setDialog(JobAttributes.DialogType.NONE);
    PageAttributes pa=new PageAttributes();
    pa.setOrigin(PageAttributes.OriginType.PRINTABLE);
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    PrintJob pjob = toolkit.getPrintJob(null, "Title", ja, pa);
    Graphics g = pjob.getGraphics();
    //draw something.....
    g.dispose();
    pjob.end();
    When using the print dialog there are no problems with changing the default printer, but I want to hide it! And when I tried to change the printer with setPrinter(...) method, nothing happened! I also tried to pass "\\\\Printer Server Name\\Shared Printer Name" to setPrinter but also nothing...
    I will appreciate any ideas, thanks in advance
    Tomecks

    I am encountering the same problem as you. setPrinter is doing nothing.
    Ideally I would like to set it using setprinter(\\\\printserver\printer);
    If you have found the soln, please post it.

  • GetResourceAsStream(String name) return null

    Hi!
    jdk1.3
    I want to get InputStream from file. My code is:
    import java.util.*;
    import java.io.*;
    String path = new String("D:" + File.separator
                   + "my_project" + File.separator
                   + "test" + File.separator
                   + "classes" + File.separator + "test.properties");// I set absolute path to file It's necessary for me
    InputStream inputStream = getClass().getResourceAsStream(path);
    Properties prop = new Properties();
    prop.load(inputStream);
    The result is NullPointerException in last row.It's can not find resource. Why?
    Thank you

    Try FileInputStream

  • AIR Application Installer screen - name - How to use image??

    I want to use the image instead of the plain text for the name of the application. Is there any way to use image as an application name?
    PrincessWidget-app.xml
    <!-- Used as the filename for the application. Required. -->
    <filename>Princess Countdown Connection</filename>
    <!-- The name that is displayed in the AIR application installer.
    May have multiple values for each language. See samples or xsd schema file. Optional. -->
    <name>assets/Princess_logo.png</name>
    <!-- An application version designator (such as "v1", "2.5", or "Alpha 1"). Required. -->
    <version>v1.0.1</version>

    thanks levi_h
    JTextPane class extends JEditPane and allows you to embed
    images or other components within the text managed by the component

  • How to reference cluster by their string name

    I have a program that contains 6 clusters of the same structure. I'd like to have a for loop to initialize the clusters to default values in stead of wiring 6 times to 6 different clusters. I've been thinking to programmably reference them by their string name, and then use an enum type to loop through their names. Is there a way to reference the cluster by name programmably?

    You can get a list of front panel objects from teh FP property and then find the controls with the names you want.
    SInce the refs to the objects will be generic array you will have to cast the refs so look over this nugget on using control references (stop after you find what you want, the nugget gets dirty at teh end).
    Have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to use txt files in jar file

    Hi all
    I just made a program that uses a text file, but I havent managed to work it correctly, program runs without jar correctly, but when I packaged all files into a jar, it couldnt find txt file, so I can only run it when I create another text file outside of jar.
    How can I solve this??

    I used this:
    Scanner fileScan = new Scanner (new file
    ("Words.txt"));
    but when I make a jar file, it doesnt find the txt
    file inside a jar,
    do I need to specify path or something?I have already told you that you shouldn't use new File(..) you should use getResourceAsStream(String name) to get an InputStream to the file.
    Kaj

  • How to use text files in RandomAccessFile both are in same Jar file

    when double click the executable jar file the class file contains the RandomAccessFile ,it will not take the text files,both the files are in jar file

    I used this:
    Scanner fileScan = new Scanner (new file
    ("Words.txt"));
    but when I make a jar file, it doesnt find the txt
    file inside a jar,
    do I need to specify path or something?I have already told you that you shouldn't use new File(..) you should use getResourceAsStream(String name) to get an InputStream to the file.
    Kaj

  • How can i use a string name as an onject name.please help!

    hi it seems like an easy one but i can not find it anywhere.how can i use the name of a string as a name of an object such as the code(my problem is the code)...
    public void oda(String name1){ 
    String name2=name1+"s";
    String name3=name1+"ss";
    TextArea name1=new TextArea();
    TextArea name2=new TextArea();
    TextArea name3=new TextArea();
    i think my problem is clear but to be sure..
    how can i give a name to an object in my textarea which is already using as a string.
    thank u .

    it get very compilcated to change the name of the object you created. identity is something you don't want to mess with..you can do it by usin reflection, but it will slow down your application and (again) is quite complicated...
    a simple solution (and more object-oriennted) is to create a Wrapper, Decorator, or Extends the class.
    example
    public class MyTextBox{
        private String name = null;
        private boolean value = false;
        private JTextArea txtArea = null;
        public MyTextBox(String name, boolean value){
            txtArea = new JTextArea();
            this.value = value;
            this.isOn = isOn;
        public String getComponentName(){  return name; }
        pubic boolean getComponentValue(){ return value; }
        public JTextArea getTextArea(){ return area; }
    }

  • How do I prompt a user to enter in a string name and set it so it can be used as an input for a DLL

    I was having problems entering in a string name and setting it. Any suggestions.

    Entering the string is easy. Just use a string control.
    To setup the Call Library Function, right click on it and select Configure. Type in the path to the DLL (or use the Browse function) and then use the Function Name dropdown box to select the function within the DLL. From here, you have to setup the parameters. The return type parameter should already be selected in the Parameter drop down box, so click on the Type drop down box and select the type of parameter that the selected function will return. From there, click on the Add Parameter After button to add an input parameter and then select the type of parameter. Continue doing this for all of the input parameters to the DLL. For strings you'll see a new drop down box appear for String Format. Choose the
    format that the DLL expects.
    You need to know what the DLL is looking for. Have fun with it.
    Rob

  • How to use Multimaps (Map String, ArrayList String )

    I was using an array to store player names, userIDs, uniqueIDs, and frag counts, but after reading about multimaps in the tutorials, it seems that would be much more efficient. However, I guess I don't quite understand it. Here's how I wanted things stored in my string array:
    String[] connectedUsers = {"user1_name", "user1_userid", "user1_uniqueid", "user1_frags"
                                            "user2_name"...}and here is how I'm attempting to setup and use the 'multimap':
    public class Main {
        static Map<String, ArrayList<String>> connectedUsers;
        public void updatePlayers(String name, String status) {
            String[] statusSplit = status.split(" ");
            if (connectedUsers.containsKey(name)) {
                connectedUsers.put(name, statusSplit[0]);
            else {
                connectedUsers.put(name, statusSplit[0]);
        }It's quite obvious I don't understand how this works, but should I even set this multimap up this way? Perhaps I should use a regular map with a string array for the values?

    You're cool MrOldie. Its just that alarm bells start ringing in my head when people come on and post as much as you do.
    * Created on Jul 28, 2005 by @author Tom Jacobs
    package tjacobs;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeSet;
    * ManyMap is a map that allows more than one value to be stored with any key
    * <p>
    * There are a number of methods in the class that have been deprecated because
    * the original functionality of Map has been violated to accomodate the concept
    * of the ManyMap
    public class ManyMap<T, T2> implements Map<T, T2> {
         private HashMap<T, ArrayList<T2>> mInnerMap;
         public ManyMap() {
              mInnerMap = new HashMap<T, ArrayList<T2>>();
          * @deprecated
         public T2 get(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.get(0);
         public Iterator<T2> getAll(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.iterator();          
         public T2 put(T obj1, T2 obj2) {
              ArrayList<T2> ar = _getNotNull(obj1);
              ar.add(obj2);
              return obj2;
         public Set<Map.Entry<T, T2>> entrySet() {
              TreeSet<Map.Entry<T, T2>> entries = new TreeSet<Map.Entry<T, T2>>();
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   Iterator<T2> vals = mInnerMap.get(key).iterator();
                   while (vals.hasNext()) {
                        Entry<T, T2> entry = new Entry<T, T2>(key, vals.next());
                        entries.add(entry);
              return entries;
         public int size() {
              return mInnerMap.size();
         public int valuesSize() {
              int vals = 0;
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   ArrayList<T2> ar = mInnerMap.get(key);
                   vals += ar.size();
              return vals;
         public void clear() {
              mInnerMap.clear();
         public void putAll(Map<? extends T, ? extends T2> map) {
              Iterator _i = map.entrySet().iterator();
              while(_i.hasNext()) {
                   Map.Entry<? extends T, ? extends T2> entry = (Map.Entry<? extends T, ? extends T2>) _i.next();
                   put(entry.getKey(), entry.getValue());
         public Collection <T2> values() {
              LinkedList ll = new LinkedList();
              Iterator<ArrayList<T2>> _i = mInnerMap.values().iterator();
              while (_i.hasNext()) {
                   ll.addAll(_i.next());
              return ll;
         public boolean containsValue(Object val) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              while (values.hasNext()) {
                   if (values.next().contains(val)) return true;
              return false;
         public boolean containsKey(Object key) {
              return mInnerMap.containsKey(key);
         public T2 remove(Object obj) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              boolean found = false;
              while (values.hasNext()) {
                   if (values.next().remove(obj)) {
                        found = true;
              return found ? (T2)obj : null;
         public boolean isEmpty() {
              return valuesSize() == 0;
         @SuppressWarnings("hiding")
         private class Entry<T, T2> implements Map.Entry<T, T2> {
              T key;
              T2 val;
              public Entry (T obj1, T2 obj2) {
                   key = obj1;
                   val = obj2;
              public T2 getValue() {
                   return val;
              public T getKey() {
                   return key;
              public T2 setValue(T2 obj) {
                   return val = obj;
         public Set<T> keySet() {
              return mInnerMap.keySet();
         public ArrayList<T2> _get (Object obj) {
              return mInnerMap.get(obj);
         public ArrayList<T2> _getNotNull (T obj) {
              ArrayList<T2> list = _get(obj);
              if (list == null) {
                   list = new ArrayList<T2>(1);
                   mInnerMap.put(obj, list);
              return list;
    }Edited by: tjacobs01 on Aug 19, 2008 12:28 PM

  • How to use string to substitude into a parameter ,look @ msg 4 more detail

    How to use a screenname from an array of strings of screennames to set it to current screen
    Example:
    //screens
    Form logo;
    List cat,sub;
    int back;//previous screen index
    public String SCREEN[]={"logo","cat","sub"};
    if (command=cmdBack) display.setCurrent(SCREEN[back]);
    how???,i don't want to type in the screen name as i want it to be able to keep track of the screen displayed.
    Please Help
    thanks

    hi...just one suggeation...u may like it ...
    u can use a stack , as and when u view a screen push it onto the stack and with each press of "back" button u pop out . this way the back button functionality works perfectly no matter how u navigate between screens .
    sanjib

  • How to use get getResourceAsStream

    Gday all,
    I gave up trying to comprehend the API doco and tutorials on the How to use get getResourceAsStream. I don't care how the class loader locates resources... I just it to work. Now!
    Here's what works... and what doesn't work...
    package krc.geometry;
    import java.util.Properties;
    import java.io.FileInputStream;
    import java.io.IOException;
    import krc.utilz.io.RuntimeIOException;
    abstract class GeometryProperties {
      private static Properties properties = new Properties();
      static {
        try {
          // properties.load(new FileInputStream("c:/java/home/src/krc/geometry/Geometry.properties")); //WORKS
          // properties.load(new FileInputStream("c:/java/home/classes/krc/geometry/Geometry.properties")); //WORKS
          // properties.load( (new Object()).getClass().getResourceAsStream("krc/geometry/Geometry.properties")); //DOES NOT WORK
          // properties.load( (new Object()).getClass().getResourceAsStream("krc.geometry.Geometry.properties")); //DOES NOT WORK
          // properties.load( (new Object()).getClass().getResourceAsStream("Geometry.properties")); //DOES NOT WORK
          // properties.load( (new Object()).getClass().getResourceAsStream("krc\\geometry\\Geometry.properties")); //DOES NOT WORK
          properties.load( (new Object()).getClass().getResourceAsStream("/krc/geometry/Geometry.properties")); //WORKS
        } catch(IOException e){
          throw new RuntimeIOException("Failed to load GeometryProperties: " + e.getMessage());
      static Properties get() {
        return properties;
      static String getProperty(String key) {
        return properties.getProperty(key);
      public static void main(String... args) {
        System.out.println(GeometryProperties.getProperty("format.double"));
    }I hope someone finds this helpful someday.
    Some related links are:
    http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemResourceAsStream(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemClassLoader()
    http://www.google.com.au/search?hl=en&q=getResourceAsStream+tutorial&meta=&btnG=Google+Search
    http://rachel.sourceforge.net/tutorial.html
    http://forum.java.sun.com/thread.jspa?threadID=5227823&messageID=9928698
    PS: I think the API has ludicrously complicated explanation of something which can be explained succinctly by example... It's a classic case of a "correct" description which only makes sense once you already know how it works. Whomever wrote that one gets 3 out of 10 stars from me... ie No bananas.
    Cheers. Keith.
    Edited by: corlettk on Dec 2, 2007 9:28 AM - typos.

    I've noticed a good google hit rate on this forum, especially on threads with meaningful a subject lines... That's how I found these forums in the first place... I'm hoping that posting solutions and comments here (as well as the occasional question) will make them available to others from google... I doubt that any site I created would earn the same "front page" status as Sun's site.
    Besides, doesn't it still cost money to setup a blog or your own homepage?
    I admit I'm intrigued despite myself... I'm aware that both http://www.joelonsoftware.com/ and http://www.dreamincode.net/ (and problably many others) started as little personal blogs.

  • How to send multiple files with it's original name over HTTPS using one CC?

    I am working on a File to HTTPs scenario. It is in production and working fine. Currently we send only one file and I have hard coded the name in the communication channel in the header fields. Now we have to send more files with different names and I want to use only one receiver channel instead of many. We need to send the files with their original names.
    I used the ASMA in the sender File Adapter and I see the FileName in the dynamic configuration under http://sap.com/xi/XI/System/File name="FileName".
    I know we can use a UDF in message mapping and get the value and put it in HEADERFIELDONE. But we don't want to use mapping as the files are huge and we don't want to insert XML tags in the payload.
    So how do I put the Filename from the DynamicConfiguration to the HTTP header field as FileName without using mapping? Are there any settings?
    Can I put something in the PROLOG or can I use any other module in the File Sender Adapter or is there any other option?
    Any help is appreciated.
    Thanks
    Sai

    See my blog:
    /people/stefan.grube/blog/2009/06/19/unknown-use-case-of-dynamicconfigurationbean-store-file-name-to-jms-header-without-mapping
    You have to put the configuration in sender channel, as HTTP adapter does not allow modules.
    For the second module, put values related to HTTP adapter.

  • How to use a regural expression to get all digit from a string.

    Hi All,
    Do you know how to use regural expression to get all digits from the following string via ABAP program?
    "'Log Attributes                 0 (  0 )     (   10 % Available  )"
    Thanks,
    Andrew

    Hi,
    Try the code mentioned below:
      DATA: STR_LEN  LIKE SY-FDPOS,
            RSTR_LEN LIKE SY-FDPOS,
            OFF      LIKE SY-FDPOS.
      DATA: IDX      LIKE SY-FDPOS,        "mn B20K054003
            CL       LIKE SY-FDPOS.        "mn B20K054003
      DATA: RSTRING(40).
      DATA: STRING(40).   " value 'A,N,I,L'.
      FIELD-SYMBOLS: <NLS_CHAR>.           "mn B20K054003
    MOVE I_REGUH-ZNME1 TO STRING.
      MOVE SPACE TO RSTRING.
      STR_LEN = STRLEN( STRING ).
      DESCRIBE FIELD RSTRING LENGTH RSTR_LEN.
      IF RSTR_LEN < STR_LEN. RAISE TOO_SMALL. ENDIF.
      WHILE IDX < STR_LEN.                 "mn B20K054003
        ASSIGN STRING+IDX(*) TO <NLS_CHAR>.   "mn B20K054003
        IF SY-LANGU EQ '2'.                "mn B20K054003
          CALL FUNCTION 'NLS_THAI_CHARLEN' "mn B20K054003
               EXPORTING                   "mn B20K054003
                    THAI_STRING  = <NLS_CHAR>       "mn B20K054003
               CHANGING                    "mn B20K054003
                    THAI_CHARLEN = CL.     "mn B20K054003
        ELSE.                              "mn B20K054003
          CL = CHARLEN( <NLS_CHAR> ).      "mn B20K054003
        ENDIF.                             "mn B20K054003
        IF IDX NE 0.                       "mn B20K054003
          SHIFT RSTRING RIGHT BY CL PLACES."mn B20K054003
        ENDIF.                             "mn B20K054003
        RSTRING+0(CL) = STRING+IDX(CL).    "mn B20K054003
        IDX = IDX + CL.                    "mn B20K054003
      ENDWHILE.                            "mn B20K054003
    Regds,
    Anil
    Edited by: Matt on Jul 1, 2009 9:36 AM -added code tags

Maybe you are looking for

  • How to implement custom Model Class in Oracle ADF?

    I am using Oracle ADF for one of my project and i am using Query component of ADF. For given tables the query component creates view objects and maps the relations. ADF uses its own custom model class for this component and it should understand the D

  • How do I get a Badge Counter in UITableViewCell on iPhone

    Hi folks, So mail has a grey oval counter with white text next to my inbox on the iPhone to show number of unread messages and various other third party apps implement the same thing. But how do they do it. It isn't built in, it isn't a label and as

  • TS1424 Whenever I try get into iTunes, it kicks me out with the message "cannot connect to iTunes"

    Hi there - whenever I go into iTunes store it automatically kickes me out with a message that reads "cannot connect to iTunes store". I don't know why it always does that - I've actually never got into the iTunes store before - Could someone help ?

  • IPhone 5 reset itself and half of my photostream got deleted!

    Im so gutted, I forgot my passlock for my iPhone and it reset itself and I had over 350 photos on photostream and when i re-activated the photostream i only have 111 for some reason. Any help would be greatly appreciated.

  • Sales Process And EDI Idocs Integration

    Hi Friends,, Good Day To You All !!!! Please enhance my knowledge with your valuable reply. I am new to ABAP and would like to learn the following . 1. Sales process - Starting from the Purchase Order Till shipment is created (All TCodes and the defi