FileHelper.java类

packagecom.east.framework.file;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.OutputStream;

importandroid.content.Context;

importandroid.os.Environment;

importandroid.os.StatFs;

publicclassFileHelper {

privateContextcontext;

privateStringSDPATH;//SD卡路径

privateStringFILESPATH;//文件路径

publicFileHelper(Context context) {

this.context= context;

SDPATH= Environment.getExternalStorageDirectory().getPath() +"//";

FILESPATH=this.context.getFilesDir().getPath() +"//";

}

/**判断SDCard是否存在?是否可以进行读写*/

publicbooleanSDCardState(){

if(Environment.getExternalStorageState().equals(

Environment.MEDIA_MOUNTED)){//表示SDCard存在并且可以读写

returntrue;

}else{

returnfalse;

}

}

/**获取SDCard文件路径*/

publicString SDCardPath(){

if(SDCardState()){//如果SDCard存在并且可以读写

SDPATH= Environment.getExternalStorageDirectory().getPath();

returnSDPATH;

}else{

returnnull;

}

}

/**获取SDCard总容量大小(MB)*/

publiclongSDCardTotal(){

if(null!= SDCardPath()&&SDCardPath().equals("")){

StatFs statfs =newStatFs(SDCardPath());

//获取SDCard的Block总数

longtotalBlocks = statfs.getBlockCount();

//获取每个block的大小

longblockSize = statfs.getBlockSize();

//计算SDCard总容量大小MB

longSDtotalSize = totalBlocks*blockSize/1024/1024;

returnSDtotalSize;

}else{

return0;

}

}

/**

*在SD卡上创建目录

*

*@paramdirName

*要创建的目录名

*@return创建得到的目录

*/

publicFile createSDDir(String dirName) {

File dir =newFile(SDPATH+ dirName);

dir.mkdir();

returndir;

}

/**

*删除SD卡上的目录

*

*@paramdirName

*/

publicbooleandelSDDir(String dirName) {

File dir =newFile(SDPATH+ dirName);

returndelDir(dir);

}

/**

*在SD卡上创建文件

*

*@throwsIOException

*/

publicFile createSDFile(String fileName)throwsIOException {

File file =newFile(SDPATH+ fileName);

file.createNewFile();

returnfile;

}

/**

*判断文件是否已经存在

*

*@paramfileName

*要检查的文件名

*@returnboolean, true表示存在,false表示不存在

*/

publicbooleanisFileExist(String fileName) {

File file =newFile(SDPATH+ fileName);

returnfile.exists();

}

/**

*删除SD卡上的文件

*

*@paramfileName

*/

publicbooleandelSDFile(String fileName) {

File file =newFile(SDPATH+ fileName);

if(file ==null|| !file.exists() || file.isDirectory())

returnfalse;

file.delete();

returntrue;

}

/**

*修改SD卡上的文件或目录名

*

*@paramfileName

*/

publicbooleanrenameSDFile(String oldfileName, String newFileName) {

File leFile =newFile(SDPATH+ oldfileName);

File newFile =newFile(SDPATH+ newFileName);

returnoleFile.renameTo(newFile);

}

/**

*拷贝SD卡上的单个文件

*

*@parampath

*@throwsIOException

*/

publicbooleancopySDFileTo(String srcFileName, String destFileName)

throwsIOException {

File srcFile =newFile(SDPATH+ srcFileName);

File destFile =newFile(SDPATH+ destFileName);

returncopyFileTo(srcFile, destFile);

}

/**

*拷贝SD卡上指定目录的所有文件

*

*@paramsrcDirName

*@paramdestDirName

*@return

*@throwsIOException

*/

publicbooleancopySDFilesTo(String srcDirName, String destDirName)

throwsIOException {

File srcDir =newFile(SDPATH+ srcDirName);

File destDir =newFile(SDPATH+ destDirName);

returncopyFilesTo(srcDir, destDir);

}

/**

*移动SD卡上的单个文件

*

*@paramsrcFileName

*@paramdestFileName

*@return

*@throwsIOException

*/

publicbooleanmoveSDFileTo(String srcFileName, String destFileName)

throwsIOException {

File srcFile =newFile(SDPATH+ srcFileName);

File destFile =newFile(SDPATH+ destFileName);

returnmoveFileTo(srcFile, destFile);

}

/**

*移动SD卡上的指定目录的所有文件

*

*@paramsrcDirName

*@paramdestDirName

*@return

*@throwsIOException

*/

publicbooleanmoveSDFilesTo(String srcDirName, String destDirName)

throwsIOException {

File srcDir =newFile(SDPATH+ srcDirName);

File destDir =newFile(SDPATH+ destDirName);

returnmoveFilesTo(srcDir, destDir);

}

/**

*将文件写入sd卡,

*/

publicOutput writeSDFile(String fileName)throwsIOException {

File file =newFile(SDPATH+ fileName);

FileOutputStream fos =newFileOutputStream(file);

returnnewOutput(fos);

}

/**

*在原有文件上继续写文件。如:appendSDFile("test.txt");

*/

publicOutput appendSDFile(String fileName)throwsIOException {

File file =newFile(SDPATH+ fileName);

FileOutputStream fos =newFileOutputStream(file,true);

returnnewOutput(fos);

}

/**

*从SD卡读取文件。如:readSDFile("test.txt");

*/

publicInput readSDFile(String fileName)throwsIOException {

File file =newFile(SDPATH+ fileName);

FileInputStream fis =newFileInputStream(file);

returnnewInput(fis);

}

/**

*建立私有文件

*

*@paramfileName

*@return

*@throwsIOException

*/

publicFile creatDataFile(String fileName)throwsIOException {

File file =newFile(FILESPATH+ fileName);

file.createNewFile();

returnfile;

}

/**

*建立私有目录

*

*@paramdirName

*@return

*/

publicFile creatDataDir(String dirName) {

File dir =newFile(FILESPATH+ dirName);

dir.mkdir();

returndir;

}

/**

*删除私有文件

*

*@paramfileName

*@return

*/

publicbooleandelDataFile(String fileName) {

File file =newFile(FILESPATH+ fileName);

returndelFile(file);

}

/**

*删除私有目录

*

*@paramdirName

*@return

*/

publicbooleandelDataDir(String dirName) {

File file =newFile(FILESPATH+ dirName);

returndelDir(file);

}

/**

*更改私有文件名

*

*@paramoldName

*@paramnewName

*@return

*/

publicbooleanrenameDataFile(String oldName, String newName) {

File ldFile =newFile(FILESPATH+ oldName);

File newFile =newFile(FILESPATH+ newName);

returnoldFile.renameTo(newFile);

}

/**

*在私有目录下进行文件复制

*

*@paramsrcFileName

*:包含路径及文件名

*@paramdestFileName

*@return

*@throwsIOException

*/

publicbooleancopyDataFileTo(String srcFileName, String destFileName)

throwsIOException {

File srcFile =newFile(FILESPATH+ srcFileName);

File destFile =newFile(FILESPATH+ destFileName);

returncopyFileTo(srcFile, destFile);

}

/**

*复制私有目录里指定目录的所有文件

*

*@paramsrcDirName

*@paramdestDirName

*@return

*@throwsIOException

*/

publicbooleancopyDataFilesTo(String srcDirName, String destDirName)

throwsIOException {

File srcDir =newFile(FILESPATH+ srcDirName);

File destDir =newFile(FILESPATH+ destDirName);

returncopyFilesTo(srcDir, destDir);

}

/**

*移动私有目录下的单个文件

*

*@paramsrcFileName

*@paramdestFileName

*@return

*@throwsIOException

*/

publicbooleanmoveDataFileTo(String srcFileName, String destFileName)

throwsIOException {

File srcFile =newFile(FILESPATH+ srcFileName);

File destFile =newFile(FILESPATH+ destFileName);

returnmoveFileTo(srcFile, destFile);

}

/**

*移动私有目录下的指定目录下的所有文件

*

*@paramsrcDirName

*@paramdestDirName

*@return

*@throwsIOException

*/

publicbooleanmoveDataFilesTo(String srcDirName, String destDirName)

throwsIOException {

File srcDir =newFile(FILESPATH+ srcDirName);

File destDir =newFile(FILESPATH+ destDirName);

returnmoveFilesTo(srcDir, destDir);

}

/**

*将文件写入应用私有的files目录。如:writeFile("test.txt");

*/

publicOutput wirteFile(String fileName)throwsIOException {

OutputStream s =context.openFileOutput(fileName,

Context.MODE_WORLD_WRITEABLE);

returnnewOutput(os);

}

/**

*在原有文件上继续写文件。如:appendFile("test.txt");

*/

publicOutput appendFile(String fileName)throwsIOException {

OutputStream s =context.openFileOutput(fileName, Context.MODE_APPEND);

returnnewOutput(os);

}

/**

*从应用的私有目录files读取文件。如:readFile("test.txt");

*/

publicInput readFile(String fileName)throwsIOException {

InputStream is =context.openFileInput(fileName);

returnnewInput(is);

}

/**

*将一个输入流中的内容写入到SD卡上生成文件

*

*@parampath

*文件目录

*@paramfileName

*文件名

*@paraminputStream

*字节输入流

*@return得到的文件

*/

publicFile writeToSDCard(String path, String fileName,

InputStream inputStream) {

File file =null;

OutputStream utput =null;

try{

createSDDir(path);

file = createSDFile(path + fileName);

utput =newFileOutputStream(file);

bytebuffer [] =newbyte[4 * 1024];

while((inputStream.read(buffer)) != -1){

output.write(buffer);

}

output.flush();

}

catch(Exception e){

e.printStackTrace();

}

finally{

try{

output.close();

}

catch(Exception e){

e.printStackTrace();

}

}

returnfile;

}

/**

*删除一个文件

*

*@paramfile

*@return

*/

publicbooleandelFile(File file) {

if(file.isDirectory())

returnfalse;

returnfile.delete();

}

/**

*删除一个目录(可以是非空目录)

*

*@paramdir

*/

publicbooleandelDir(File dir) {

if(dir ==null|| !dir.exists() || dir.isFile()) {

returnfalse;

}

for(File file : dir.listFiles()) {

if(file.isFile()) {

file.delete();

}elseif(file.isDirectory()) {

delDir(file);//递归

}

}

dir.delete();

returntrue;

}

/**

*拷贝一个文件,srcFile源文件,destFile目标文件

*

*@parampath

*@throwsIOException

*/

publicbooleancopyFileTo(File srcFile, File destFile)throwsIOException {

if(srcFile.isDirectory() || destFile.isDirectory())

returnfalse;//判断是否是文件

FileInputStream fis =newFileInputStream(srcFile);

FileOutputStream fos =newFileOutputStream(destFile);

intreadLen = 0;

byte[] buf =newbyte[1024];

while((readLen = fis.read(buf)) != -1) {

fos.write(buf, 0, readLen);

}

fos.flush();

fos.close();

fis.close();

returntrue;

}

/**

*拷贝目录下的所有文件到指定目录

*

*@paramsrcDir

*@paramdestDir

*@return

*@throwsIOException

*/

publicbooleancopyFilesTo(File srcDir, File destDir)throwsIOException {

if(!srcDir.isDirectory() || !destDir.isDirectory())

returnfalse;//判断是否是目录

if(!destDir.exists())

returnfalse;//判断目标目录是否存在

File[] srcFiles = srcDir.listFiles();

for(inti = 0; i < srcFiles.length; i++) {

if(srcFiles[i].isFile()) {

//获得目标文件

File destFile =newFile(destDir.getPath() +"//"

+ srcFiles[i].getName());

copyFileTo(srcFiles[i], destFile);

}elseif(srcFiles[i].isDirectory()) {

File theDestDir =newFile(destDir.getPath() +"//"

+ srcFiles[i].getName());

copyFilesTo(srcFiles[i], theDestDir);

}

}

returntrue;

}

/**

*移动一个文件

*

*@paramsrcFile

*@paramdestFile

*@return

*@throwsIOException

*/

publicbooleanmoveFileTo(File srcFile, File destFile)throwsIOException {

booleaniscopy = copyFileTo(srcFile, destFile);

if(!iscopy)

returnfalse;

delFile(srcFile);

returntrue;

}

/**

*移动目录下的所有文件到指定目录

*

*@paramsrcDir

*@paramdestDir

*@return

*@throwsIOException

*/

publicbooleanmoveFilesTo(File srcDir, File destDir)throwsIOException {

if(!srcDir.isDirectory() || !destDir.isDirectory()) {

returnfalse;

}

File[] srcDirFiles = srcDir.listFiles();

for(inti = 0; i < srcDirFiles.length; i++) {

if(srcDirFiles[i].isFile()) {

File neDestFile =newFile(destDir.getPath() +"//"

+ srcDirFiles[i].getName());

moveFileTo(srcDirFiles[i], oneDestFile);

delFile(srcDirFiles[i]);

}elseif(srcDirFiles[i].isDirectory()) {

File neDestFile =newFile(destDir.getPath() +"//"

+ srcDirFiles[i].getName());

moveFilesTo(srcDirFiles[i], oneDestFile);

delDir(srcDirFiles[i]);

}

}

returntrue;

}

}

Input.java帮助类

packagecom.sinous.framework.file;

importjava.io.ByteArrayOutputStream;

importjava.io.EOFException;

importjava.io.IOException;

importjava.io.InputStream;

importjava.io.UTFDataFormatException;

publicclassInputextendsInputStream {

privatestaticfinalintDEFAULT_BUFFER_SIZE= 1024;

privatebyte[]buf;

privateintpos;

privateintcount;

privateInputStreamin;

publicInput(InputStream in) {

this(in,DEFAULT_BUFFER_SIZE);

}

publicInput(InputStream in,intbufferSize) {

this.in= in;

buf=newbyte[bufferSize];

}

publicvoidclose()throwsIOException {

buf=null;

in.close();

}

publicintread()throwsIOException {

if(pos>=count||pos>=buf.length) {

pos= 0;

count=in.read(buf, 0,DEFAULT_BUFFER_SIZE);

}

if(pos>=count) {

return-1;

}

returnbuf[pos++] & 0xff;

}

publicintread(byte[] b)throwsIOException {

returnread(b, 0, b.length);

}

publicintread(byte[] b,intoff,intlen)throwsIOException {

intremain =count-pos;

if(remain >= (len - off)) {

System.arraycopy(buf,pos, b, off, len);

pos+= len;

returnlen;

}else{

if(remain > 0) {

System.arraycopy(buf,pos, b, off, remain);

pos+= remain;

intnewRemain = len - remain;

byte[] remainData =newbyte[newRemain];

intrd =in.read(remainData, 0, newRemain);

System.arraycopy(remainData, 0, b, off + remain, rd);

returnremain + rd;

}else{

intrd =in.read(b, off, len);

returnrd;

}

}

}

publicbooleanreadBoolean()throwsIOException {

intch = read();

if(ch < 0) {

thrownewEOFException();

}

return(ch != 0);

}

publicintreadUnsignedByte()throwsIOException {

intch = read();

if(ch < 0) {

thrownewEOFException();

}

returnch;

}

publicintreadUnsignedShort()throwsIOException {

intch1 = read();

intch2 = read();

if((ch1 | ch2) < 0) {

thrownewEOFException();

}

return(ch1 << 8) + (ch2 << 0);

}

publicshortreadShort()throwsIOException {

intch1 = read();

intch2 = read();

if((ch1 | ch2) < 0) {

thrownewEOFException();

}

return(short) ((ch1 << 8) + (ch2 << 0));

}

publiccharreadChar()throwsIOException {

intch1 = read();

intch2 = read();

if((ch1 | ch2) < 0) {

thrownewEOFException();

}

return(char) ((ch1 << 8) + (ch2 << 0));

}

publicintreadInt()throwsIOException {

intch1 = read();

intch2 = read();

intch3 = read();

intch4 = read();

if((ch1 | ch2 | ch3 | ch4) < 0) {

thrownewEOFException();

}

return((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));

}

publiclongreadLong()throwsIOException {

return((long) (readInt()) << 32) + (readInt() & 0xFFFFFFFFL);

}

publicfloatreadFloat()throwsIOException {

returnFloat.intBitsToFloat(readInt());

}

publicdoublereadDouble()throwsIOException {

returnDouble.longBitsToDouble(readLong());

}

publicString readUTF8()throwsIOException {

intutflen = readUnsignedShort();

if(utflen <= 0) {

return"";

}

charstr[] =newchar[utflen];

bytebytearr[] =newbyte[utflen];

intc, char2, char3;

intcount = 0;

intstrlen = 0;

read(bytearr);

while(count < utflen) {

c = (int) bytearr[count] & 0xff;

switch(c >> 4) {

case0:

case1:

case2:

case3:

case4:

case5:

case6:

case7:

/* 0xxxxxxx */

count++;

str[strlen++] = (char) c;

break;

case12:

case13:

/* 110xxxxx10xxxxxx*/

count += 2;

if(count > utflen) {

thrownewUTFDataFormatException();

}

char2 = (int) bytearr[count - 1];

if((char2 & 0xC0) != 0x80) {

thrownewUTFDataFormatException();

}

str[strlen++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F));

break;

case14:

/* 1110xxxx10xxxxxx10xxxxxx*/

count += 3;

if(count > utflen) {

thrownewUTFDataFormatException();

}

char2 = (int) bytearr[count - 2];

char3 = (int) bytearr[count - 1];

if(((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) {

thrownewUTFDataFormatException();

}

str[strlen++] = (char) (((c & 0x0F) << 12)

| ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));

break;

default:

/* 10xxxxxx, 1111xxxx*/

thrownewUTFDataFormatException();

}

}

// The number of chars produced may be less thanutflen

returnnewString(str, 0, strlen);

}

publicSerializable readSerializable()throwsIOException {

String className = readUTF8();

Serializable serializable =null;

try{

serializable = (Serializable) Class.forName(className).newInstance();

serializable.deserialize(this);

}catch(Exception e) {

thrownewIOException(e.toString());

}

returnserializable;

}

publicbyte[] readAll()throwsIOException {

ByteArrayOutputStream baos =newByteArrayOutputStream();

intch;

byte[] buffer =newbyte[1024];

while((ch =in.read(buffer)) != -1) {

baos.write(buffer, 0, ch);

}

byte[] ret = baos.toByteArray();

baos.close();

returnret;

}

}

Output.java帮助类

packagecom.sinous.framework.file;

importjava.io.IOException;

importjava.io.OutputStream;

importjava.io.UTFDataFormatException;

publicclassOutputextendsOutputStream {

privatestaticfinalintDEFAULT_BUFFER_SIZE= 1024;

privatebyte[]buf;

privateintcount;

privateOutputStreamout;

publicOutput(OutputStream out) {

this(out,DEFAULT_BUFFER_SIZE);

}

publicOutput(OutputStream out,intbufferSize) {

this.out= out;

buf=newbyte[bufferSize];

}

privatevoidflushBuffer()throwsIOException {

if(count> 0) {

out.write(buf, 0,count);

count= 0;

}

}

publicvoidflush()throwsIOException {

flushBuffer();

out.flush();

}

publicvoidclose()throwsIOException {

flush();

buf=null;

out.close();

}

publicvoidwrite(intb)throwsIOException{

if(count>=buf.length) {

flushBuffer();

}

buf[count++] = (byte) b;

}

publicvoidwrite(byte[] b)throwsIOException {

write(b, 0, b.length);

}

publicvoidwrite(byte[] b,intoff,intlen)throwsIOException {

if(len >=buf.length) {

flushBuffer();

out.write(b, off, len);

return;

}elseif(len >buf.length-count) {

flushBuffer();

}

System.arraycopy(b, off,buf,count, len);

count+= len;

}

publicvoidwriteBoolean(booleanv)throwsIOException {

write(v ? 1 : 0);

}

publicvoidwriteShort(intv)throwsIOException {

write((v >>> 8) & 0xFF);

write(v & 0xFF);

}

publicvoidwriteChar(intv)throwsIOException {

write((v >>> 8) & 0xFF);

write(v & 0xFF);

}

publicvoidwriteInt(intv)throwsIOException {

write((v >>> 24) & 0xFF);

write((v >>> 16) & 0xFF);

write((v >>> 8) & 0xFF);

write(v & 0xFF);

}

publicvoidwriteLong(longv)throwsIOException {

write((int) (v >>> 56) & 0xFF);

write((int) (v >>> 48) & 0xFF);

write((int) (v >>> 40) & 0xFF);

write((int) (v >>> 32) & 0xFF);

write((int) (v >>> 24) & 0xFF);

write((int) (v >>> 16) & 0xFF);

write((int) (v >>> 8) & 0xFF);

write((int) v & 0xFF);

}

publicvoidwriteFloat(floatv)throwsIOException {

writeInt(Float.floatToIntBits(v));

}

publicvoidwriteDouble(doublev)throwsIOException {

writeLong(Double.doubleToLongBits(v));

}

publicvoidwriteUTF8(String str)throwsIOException {

if(str ==null) {

str ="";

}

intstrlen = str.length();

intutflen = 0;

char[] charr =newchar[strlen];

intc, count = 0;

str.getChars(0, strlen, charr, 0);

for(inti = 0; i < strlen; i++) {

c = charr[i];

if((c >= 0x0001) && (c <= 0x007F)) {

utflen++;

}elseif(c > 0x07FF) {

utflen += 3;

}else{

utflen += 2;

}

}

if(utflen > 65535) {

thrownewUTFDataFormatException();

}

byte[] bytearr =newbyte[utflen + 2];

bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);

bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);

for(inti = 0; i < strlen; i++) {

c = charr[i];

if((c >= 0x0001) && (c <= 0x007F)) {

bytearr[count++] = (byte) c;

}elseif(c > 0x07FF) {

bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));

bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F));

bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));

}else{

bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));

bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));

}

}

write(bytearr);

}

publicvoidwriteSerializable(Serializable serializable)throwsIOException {

writeUTF8(serializable.getClass().getName());

serializable.serialize(this);

}

}

Serializable.java序列化接口

packagecom.sinous.framework.file;

importjava.io.IOException;

publicinterfaceSerializable{

publicvoidserialize(Output out)throwsIOException;

publicvoiddeserialize(Input in)throwsIOException;

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐