读取内存卡的文件方法读取内存卡的文件方法
J2ME读取手机内存卡里的文本文件.txt【原创】 2009-04-01 15:47 /*
* To change this template, choose Tools | Templates
* and open the template in the editor. * 2009-03-19 10:12
*/
package Forms;
import java.io.ByteArrayOutputStream; import java.io.IOException;
import j...
读取内存卡的文件方法
J2ME读取手机内存卡里的文本文件.txt【原创】 2009-04-01 15:47 /*
* To change this template, choose Tools | Templates
* and open the template in the editor. * 2009-03-19 10:12
*/
package Forms;
import java.io.ByteArrayOutputStream; import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connection; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection;
/**
*
* 专门用来读取内存卡里的.txt文件 * @author Acheng
*/
public class ReadTextForm implements Runnable {
/**
* 文件路径
*/
private String ref = null;
/**
* 读文件的线程
*/
private Thread readThread;
/**
* 用来保存读取到的文本
*/
private String s = null;
public ReadTextForm()
{
}
/**
* 启动该线程
* @param ref 要读取的文件路径,比如读取内存卡里的help_en.txt文件
路径:"file://localhost/e:/SmartMacau/main/help_en.txt"
*/
public void startThread( String ref )
{
this.ref = ref;
if( readThread != null )
{
readThread = null;
}
readThread = new Thread( this );
readThread.start();
}
public void run()
{
InputStream in = null;
Connection conn = null;
ByteArrayOutputStream baos = null;
if( ref.startsWith( "file:" ) )//读内存卡里的文件
{
try
{
conn = ( FileConnection ) Connector.open( ref );
in = ( ( FileConnection ) conn ).openInputStream();
// in.skip( 2 );
baos = new ByteArrayOutputStream();
int ch = 0;
while( ( ch = in.read() ) != -1 )
{
baos.write( ch );
}
byte[] tmp = baos.toByteArray();
//UTF-8编码,中文时,文件开头是框框,英文不会出现这个情
况
s = new String( tmp, "UTF-8" );
//跳过文件开头的框框
if( tmp[0] == -17 && tmp[1] == -69 && tmp[2] == -65 )
{
s = s.substring( 1 );
}
// String s = new String(baos.toString().getBytes("ISO8859_1"),"GBK");//乱码
// String s = new String(baos.toString().getBytes("ISO8859_1"),"UTF-8");//文件开头是框
框
// String s = baos.toString();//乱码 // String s = new String( tmp);
} catch( IOException ex )
{
ex.printStackTrace();
} finally
{
if( baos != null )
{
try
{
baos.close();
} catch( IOException ex )
{
ex.printStackTrace();
}
baos = null;
}
if( in != null )
{
try
{
in.close();
} catch( IOException ex )
{
ex.printStackTrace();
}
in = null;
}
if( conn != null )
{
try
{
conn.close();
} catch( IOException ex )
{
ex.printStackTrace();
}
conn = null;
}
}
}
else
{
System.out.println( "ReadTextForm 路径有问题:" );
System.out.println( "Readurl::" + ref );
}
}
/**
* 获取读取到的文本
*/
public String getText()
{
return s;
}
}
本文档为【读取内存卡的文件方法】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。