super.onCreate(savedInstanceState)
setContentView(R.layout.main)
String fileName = "/sdcard/y.txt"//文件路径
// 也可以用String fileName = "mnt/sdcard/Y.txt"
String res = ""
try {
FileInputStream fin = new FileInputStream(fileName)
// FileInputStream fin = openFileInput(fileName)
// 用这个就不行了,必须用FileInputStream
int length = fin.available()
byte[] buffer = new byte[length]
fin.read(buffer)
res = EncodingUtils.getString(buffer, "UTF-8")////依Y.txt的编码类型选择合适的编码,如果不调整会乱码
fin.close()//关闭资源
System.out.println("res--->"+res)
int a=Integer.parseInt(res.substring(3, 5))
int b=Integer.parseInt(res.substring(8, 10))
System.out.println(a+"res--->"+b)//获取的a.b
} catch (Exception e) {
e.printStackTrace()
}
}
方法:
通过输入流的readline方法进行按行读取内容。
举例:
public static void readFileOnLine(String filePath){//输入文件路径FileInputStream fis = openFileInput(filePath)//打开文件输入流
StringBuffer sBuffer = new StringBuffer()
DataInputStream dataIO = new DataInputStream(fis)//读取文件数据流
String strLine = null
while((strLine = dataIO.readLine()) != null) {//通过readline按行读取
sBuffer.append(strLine + "\n")//strLine就是一行的内容
}
dataIO.close()
fis.close()
}
1. 读取 *** 作String path = "/sdcard/foo.txt"
String content = ""//文件内容字符串
//打开文件
File file = new File(path)
//如果path是传递过来的参数,可以做一个非目录的判断
if (file.isDirectory()){
Toast.makeText(EasyNote.this, "没有指定文本文件!", 1000).show()
}
else{
try {
InputStream instream = new FileInputStream(file)
if (instream != null) {
InputStreamReader inputreader = new InputStreamReader(instream)
BufferedReader buffreader = new BufferedReader(inputreader)
String line
//分行读取
while (( line = buffreader.readLine()) != null) {
content += line + "\n"
}
instream.close()
} catch (java.io.FileNotFoundException e) {
Toast.makeText(EasyNote.this, "文件不存在", Toast.LENGTH_SHORT).show()
} catch (IOException e) {
e.printStackTrace()
}
}
2. 写入 *** 作
String filePath = "/sdcard/foo2.txt"
String content = "这是将要写入到文本文件的内容"
//如果filePath是传递过来的参数,可以做一个后缀名称判断; 没有指定的文件名没有后缀,则自动保存为.txt格式
if(!filePath.endsWith(".txt") &&!filePath.endsWith(".log"))
filePath += ".txt"
//保存文件
File file = new File(filePath)
try {
OutputStream outstream = new FileOutputStream(file)
OutputStreamWriter out = new OutputStreamWriter(outstream)
out.write(content)
out.close()
} catch (java.io.IOException e) {
e.printStackTrace()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)