Tuesday, January 27, 2009

Code: Add plain text or binary files to an application


The class java.lang.Class contains methods that enable you to import a plain text or a binary file as an input stream. Once the contents of the file are in an input stream it can be read appropriately into the necessary format. Below is an example on how to import a plain text file into an application.

1. Open a text editor and add some text. For example, Test test test
2. Save the file as test.
3. Create a new project.
4. Add the file text to the project.
5. Create a new file called FileDemo.java.

The source for FileDemo.java looks as follows;
Code:
package com.packagename.stuff;


import java.io.*;

import net.rim.device.api.system.*;


class FileDemo extends Application {


public static void main(String args[]) {

FileDemo theApp = new FileDemo();

theApp.enterEventDispatcher();

}


public FileDemo() {

try {

//The class name is the fully qualified package name followed

//by the actual name of this class

Class classs = Class.forName("com.packagename.stuff.FileDemo");


//to actually retrieve the resource prefix the name of the file with a "/"

InputStream is = classs.getResourceAsStream("/test");


//we now have an input stream. Create a reader and read out

//each character in the stream.

InputStreamReader isr = new InputStreamReader(is);

char c;

while ((c = (char)isr.read()) != -1) {

System.out.print(c);

}

} catch(Exception ex) {

System.out.println("Error: " + ex.toString());

}

}

}
When the above demo is run in the simulator the debugger will show the output of "Test test test" or the contents in the test file.

1 comment:

Place your comments here...