Read text files in various formats in J2ME

xiaoxiao2021-03-06  43

In J2ME development, we often save a text message in a TXT format text file as a resource. This makes it easy to modify and manage. Then read them will be some difficult for some friends who just contact J2ME. A few days ago Under, read some brothers' articles and code, summarize three methods to read Unicode, UTF-8, Unicode Big Endian format ... This article does not consider reading efficiency issues.

Both methods can read Chinese and English characters. The array length used to store the length of the text.

There is also some ways to read English characters that are not listed.

First, read Unicode format

private String read_Uni (String resource) {byte word_uni [] = new byte [1024]; String strReturn = ""; InputStream is;. try {is = getClass () getResourceAsStream (resource); is.read (word_uni); is. Close (); stringbuffer stringbuffer = new stringbuffer (""); for (int J = 0; j

Second, read UTF-8 format

public String read_UTF (String name) {String strReturn = ""; InputStream in = null; byte [] word_utf = new byte [1024]; try {in = getClass () getResourceAsStream (name);. in.read (word_utf); In.close (); strreturn = new string (Word_UTF, "UTF-8");} catch (exception e) {system.out.println ("Readutf error:" E.toString ());} finally {in = NULL;} Return strreturn;} III, read Unicode Big Endian format

When reading the Unicode Big Endian format, use the READCHAR () method to read, so the char array is stored.

Note: Add '$' at the end of the text, the end of the text.

Different line 10 line dis.skip (2) is a 5-character file number, if these two headers are saved with Microsoft NotePad.

Of course, you can use UltraEdit to delete these two headers first, then use new files, copy paste, save as other formats. This two headers are gone ..

private String read_Uni_b_e (String resource) {char word_uni_b_e [] = new char [1024]; String strReturn = ""; DataInputStream dis; try {dis = new DataInputStream (getClass () getResourceAsStream (resource).); int counter = 0; Dis.skip (2); char Temp; while (true) {TEMP = Dis.readChar (); if (Temp == '$') Break; Word_uni_b_e [counter ] = Temp;} disilry (); strreturn = String.Valueof (Word_uni_b_e, 0, counter;} catch (exception e) {system.out.println ("read_uni_b_e error!" E.getMessage ());} finally {div = null;} Return Strreturn;

The above three methods test platforms:

Operation System: Microsoft Windows XP Professional Service Pack 1emulator: Sun Wireless Toolkit 2.2 Beta DefaultColorPhone

转载请注明原文地址:https://www.9cbs.com/read-57725.html

New Post(0)