日期:2014-05-20  浏览次数:20790 次

读取txt格式里的数据并执行
javame  怎么从txt格式的文档里读取数据并执行
------解决方案--------------------
根据路径找到文件然后转换成字符串就可以使用了。

给你个例子
fileName 就是你要打开的文件路径,用的时候调用这个方法,根据自己的需要去截取

private String readFile(String fileName)
    {
        try
        {
            String res = "";
            InputStream is = getResources().getAssets().open(fileName);
            int length = is.available();
            byte[] buffer = new byte[length];
            is.read(buffer);
            res = EncodingUtils.getString(buffer, "uft-8");
            return res;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }


------解决方案--------------------

package com.jctest.one;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class ReadText {
public String ReadDate() { 
String url = "c:/test.txt"; 
String strs = "";
try { 
FileReader read = new FileReader(new File(url)); 
StringBuffer sb = new StringBuffer(); 
char ch[] = new char[1024]; 
int d = read.read(ch); 
while(d!=-1){ 
String str = new String(ch,0,d); 
sb.append(str); 
d = read.read(ch); 

System.out.print(sb.toString()); 
String a = sb.toString().replaceAll("@@@@@", ","); 
strs = a.substring(0,a.length()-1); 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 

return strs ; 

public static void main(String a[]) 

ReadText util = new ReadText(); 
String cc = util.ReadDate(); 
System.out.println("result...."+cc); 

}


经过测试没有任何问题。楼主可以直接复制到类中运行,记得把要读取的文件放在C盘。