android项目之记事本-2(文件保存与阅读)

欢迎你继续阅读android项目实战记事本系列教程 本系列会介绍一个完整的上线项目开发过程

欢迎下载本app 如果需要源码 请加qq群 531314820  一起学习

应用下载地址: http://shouji.baidu.com/software/9544563.html 

项目架构:

版本 sdk 4.2 ,开发工具eclipse adt 

项目结构图


进入主题 输入数据保存 本版本只保留为.txt格式 后期可以扩展

主要核心功能无非就是io流是使用 我这里写了一个工具类,直接上代码吧  里面有注释

FileUtilt.java

package com.singleton.sjsb.tools;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import android.content.Context;
import android.os.Environment;
import android.widget.Toast;

/**
 * 文件或文件夹操作 
 * @author singleton-zw
 * Date: 2014-3-5
 */
public class FileUtilt {
	private Context context;// 上下文对象,有快速得到输入流的方法

	public FileUtilt(Context context) {
		this.context = context;
	}

	/**
	 * 把文件保存在sd 卡
	 * @param fileName 文件名
	 * @param fileContent 文件内容
	 * @param path 路径
	 * @param charset 编码格式 默认为utf-8
	 * @throws Exception
	 */
	public void saveSdcard(String fileName, String fileContent, String path,String charset)throws Exception {
		// 判断sd 卡是否存在,是否读写
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			File file = new File(new File(path), fileName);
//			java.io.File file = new java.io.File(Environment
//					.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+fileName);
//			 File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//			    File file = File.createTempFile(fileName, ".txt", storageDir);
			if(charset==null){
				FileOutputStream outStream = new FileOutputStream(file); 
				outStream.write(fileContent.getBytes());// UTF-8
				outStream.close();
			}else{
				OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),charset);   
		        BufferedWriter writer=new BufferedWriter(write);     
		        writer.write(fileContent);   
		        writer.close();  
			}
		} else {
			Toast.makeText(context, "没有SD卡", 1).show();
		}
		
	}

	/**
	 * 读 操作
	 * @param filename 文件名
	 * @param path  路径
	 * @return charset 编码格式
	 */
	private String CHARSET="UTF-8";//默认读出编码格式
	public String read(String filename, String path) {
		CHARSET = getFilecharset(new File(path + "/"+ filename));//得到文件的编码格式
//		System.out.println(CHARSET+"---");
		try {
			FileInputStream inStream = new FileInputStream(new File(path + "/"+ filename));
			byte[] buffer = new byte[inStream.available()];
			inStream.read(buffer);
			inStream.close();
			return new String(buffer, CHARSET);// 转码
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 通过下边方法获取文本文件编码格式,然后以指定的编码读取文件,就不会出现乱码(简单测试了一下,但是也不保证100%)
	 * @param sourceFile
	 * @return charset 编码格式
	 */
	private String getFilecharset(File sourceFile) {
		String charset = "GBK";
		byte[] first3Bytes = new byte[3];
		try {
			boolean checked = false;
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
			bis.mark(0);
			int read = bis.read(first3Bytes, 0, 3);
			if (read == -1) {
				return charset; // 文件编码为 ANSI
			} else if (first3Bytes[0] == (byte) 0xFF
					&& first3Bytes[1] == (byte) 0xFE) {
				charset = "UTF-16LE"; // 文件编码为 Unicode
				checked = true;
			} else if (first3Bytes[0] == (byte) 0xFE
					&& first3Bytes[1] == (byte) 0xFF) {
				charset = "UTF-16BE"; // 文件编码为 Unicode big endian
				checked = true;
			} else if (first3Bytes[0] == (byte) 0xEF
					&& first3Bytes[1] == (byte) 0xBB
					&& first3Bytes[2] == (byte) 0xBF) {
				charset = "UTF-8"; // 文件编码为 UTF-8
				checked = true;
			}
			bis.reset();
			if (!checked) {
				int loc = 0;
				while ((read = bis.read()) != -1) {
					loc++;
					if (read >= 0xF0)
						break;
					if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK
						break;
					if (0xC0 <= read && read <= 0xDF) {
						read = bis.read();
						if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
							// (0x80
							// - 0xBF),也可能在GB编码内
							continue;
						else
							break;
					} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小
						read = bis.read();
						if (0x80 <= read && read <= 0xBF) {
							read = bis.read();
							if (0x80 <= read && read <= 0xBF) {
								charset = "UTF-8";
								break;
							} else
								break;
						} else
							break;
					}
				}
			}
			bis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return charset;
	}
}

上面就主要核心代码  文件操作 基本都是一些io操作  需要注意的是 getFilecharset 方法是阅读的时候判断文件的格式编码

接下来介绍 在主页面使用工具类 进行文件保存

主页面布局(由于注重功能的实现 就没过多的进行ui设计(好吧 本人ui做的太差  ))

主要就是一个EditText 控件

ui_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ui_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00000000"
    android:orientation="vertical" >
    <!-- 主界面 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv_testsize"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_weight="10"
            android:text="当前字数:"
            android:textSize="13sp" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/toumin"
            android:onClick="ju"
            android:text="diabji" />
    </LinearLayout>

    <EditText
        android:id="@+id/neiron"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#00000000"
        android:gravity="top|left" />
    
</LinearLayout>


主要分为上下两部分 上部分显示当前字数 和 一个隐藏编辑区也就是下半部分的button

本文只介绍保存的操作  其他操作接下来视频介绍

FileUtilt service = new FileUtilt(getApplicationContext());
				fnei = neiron.getText().toString();
				// 文件名不变
				service.saveSdcard(filenames, fnei, savepath,null);
				Toast.makeText(getApplicationContext(), "保存成功", 1).show();
以上是核心代码数据保存 
如果有不懂的可联系我 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值