ToolFile.java 16.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
package com.cnlive.goldenline.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.NonNull;
import android.util.Log;

/**
 * 文件工具类
 */
public class ToolFile {

	private static final String TAG = ToolFile.class.getSimpleName();

	/**
	 * 检查是否已挂载SD卡镜像(是否存在SD卡)
	 * 
	 * @return
	 */
	public static boolean isMountedSDCard() {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			return true;
		} else {
			Log.w(TAG, "SDCARD is not MOUNTED !");
			return false;
		}
	}

	/**
	 * 获取SD卡剩余容量(单位Byte)
	 * 
	 * @return
	 */
	public static long gainSDFreeSize() {
		if (isMountedSDCard()) {
			// 取得SD卡文件路径
			File path = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(path.getPath());
			// 获取单个数据块的大小(Byte)
			long blockSize = sf.getBlockSize();
			// 空闲的数据块的数量
			long freeBlocks = sf.getAvailableBlocks();

			// 返回SD卡空闲大小
			return freeBlocks * blockSize; // 单位Byte
		} else {
			return 0;
		}
	}

	/**
	 * 获取SD卡总容量(单位Byte)
	 * 
	 * @return
	 */
	public static long gainSDAllSize() {
		if (isMountedSDCard()) {
			// 取得SD卡文件路径
			File path = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(path.getPath());
			// 获取单个数据块的大小(Byte)
			long blockSize = sf.getBlockSize();
			// 获取所有数据块数
			long allBlocks = sf.getBlockCount();
			// 返回SD卡大小(Byte)
			return allBlocks * blockSize;
		} else {
			return 0;
		}
	}

	/**
	 * 获取可用的SD卡路径(若SD卡不没有挂载则返回"")
	 * 
	 * @return
	 */
	public static String gainSDCardPath() {
		if (isMountedSDCard()) {
			File sdcardDir = Environment.getExternalStorageDirectory();
			if (!sdcardDir.canWrite()) {
				Log.w(TAG, "SDCARD can not write !");
			}
			return sdcardDir.getPath();
		}
		return "";
	}

	/**
	 * 以行为单位读取文件内容,一次读一整行,常用于读面向行的格式化文件
	 * @param filePath 文件路径
	 */
	public static String readFileByLines(@NonNull String filePath) throws IOException
	{
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try
		{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),System.getProperty("file.encoding")));
			String tempString = null;
			while ((tempString = reader.readLine()) != null)
			{
				sb.append(tempString);
				sb.append("\n");
			}
			reader.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			if (reader != null){reader.close();}
		}

		return sb.toString();

	}
	
	/**
	 * 以行为单位读取文件内容,一次读一整行,常用于读面向行的格式化文件
	 * @param filePath 文件路径
	 * @param encoding 写文件编码
	 */
	public static String readFileByLines(@NonNull String filePath, @NonNull String encoding) throws IOException
	{
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try
		{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),encoding));
			String tempString = null;
			while ((tempString = reader.readLine()) != null)
			{
				sb.append(tempString);
				sb.append("\n");
			}
			reader.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			if (reader != null){reader.close();}
		}

		return sb.toString();
	}
	
	
	/**
	 * 保存内容
	 * @param filePath 文件路径
	 * @param content 保存的内容
	 * @throws IOException
	 */
	public static void saveToFile(@NonNull String filePath, @NonNull String content) throws IOException
	{
		saveToFile(filePath,content,System.getProperty("file.encoding"));
	}

	/**
	 * 指定编码保存内容
	 * @param filePath 文件路径
	 * @param content 保存的内容
	 * @param encoding 写文件编码
	 * @throws IOException
	 */
	public static void saveToFile(@NonNull String filePath, @NonNull String content, @NonNull String encoding) throws IOException
	{
		BufferedWriter writer = null;
		File file = new File(filePath);
		try
		{
			if(!file.getParentFile().exists())
			{
				file.getParentFile().mkdirs();
			}
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), encoding));
			writer.write(content);

		} finally
		{
			if (writer != null){writer.close();}
		}
	}
	
	/**
	 * 追加文本
	 * @param content 需要追加的内容
	 * @param file 待追加文件源
	 * @throws IOException
	 */
	public static void appendToFile(@NonNull String content, @NonNull File file) throws IOException
	{
		appendToFile(content, file, System.getProperty("file.encoding"));
	}

	/**
	 * 追加文本
	 * @param content 需要追加的内容
	 * @param file 待追加文件源
	 * @param encoding 文件编码
	 * @throws IOException
	 */
	public static void appendToFile(@NonNull String content, @NonNull File file, @NonNull String encoding) throws IOException
	{
		BufferedWriter writer = null;
		try
		{
			if(!file.getParentFile().exists())
			{
				file.getParentFile().mkdirs();
			}
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), encoding));
			writer.write(content);
		} finally
		{
			if (writer != null){writer.close();}
		}
	}
	
	/**
	 * 判断文件是否存在
	 * @param filePath 文件路径
	 * @return 是否存在
	 * @throws Exception
	 */
	@NonNull
	public static Boolean isExsit(@NonNull String filePath)
	{
		Boolean flag = false ;
		try
		{
			File file = new File(filePath);
			if(file.exists())
			{
				flag = true;
			}
		}catch(Exception e){
			System.out.println("判断文件失败-->"+e.getMessage()); 
		} 
		
		return flag;
	}
	
	/**
	 * 快速读取程序应用包下的文件内容
	 * 
	 * @param context
	 *            上下文
	 * @param filename
	 *            文件名称
	 * @return 文件内容
	 * @throws IOException
	 */
	@NonNull
	public static String read(@NonNull Context context, String filename) throws IOException {
		FileInputStream inStream = context.openFileInput(filename);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		return new String(data);
	}

	/**
	 * 读取指定目录文件的文件内容
	 * 
	 * @param fileName
	 *            文件名称
	 * @return 文件内容
	 * @throws Exception
	 */
	@NonNull
	public static String read(@NonNull String fileName) throws IOException {
		FileInputStream inStream = new FileInputStream(fileName);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		return new String(data);
	}

	/***
	 * 以行为单位读取文件内容,一次读一整行,常用于读面向行的格式化文件
	 * 
	 * @param fileName
	 *            文件名称
	 * @param encoding
	 *            文件编码
	 * @return 字符串内容
	 * @throws IOException
	 */
	public static String read(@NonNull String fileName, @NonNull String encoding)
			throws IOException {
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(fileName), encoding));
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				sb.append(tempString);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		return sb.toString();
	}

	/**
	 * 读取raw目录的文件内容
	 * 
	 * @param context
	 *            内容上下文
	 * @param rawFileId
	 *            raw文件名id
	 * @return
	 */
	@NonNull
	public static String readRawValue(@NonNull Context context, int rawFileId) {
		String result = "";
		try {
			InputStream is = context.getResources().openRawResource(rawFileId);
			int len = is.available();
			byte[] buffer = new byte[len];
			is.read(buffer);
			result = new String(buffer, "UTF-8");
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 读取assets目录的文件内容
	 * 
	 * @param context
	 *            内容上下文
	 * @param fileName
	 *            文件名称,包含扩展名
	 * @return
	 */
	@NonNull
	public static String readAssetsValue(@NonNull Context context, String fileName) {
		String result = "";
		try {
			InputStream is = context.getResources().getAssets().open(fileName);
			int len = is.available();
			byte[] buffer = new byte[len];
			is.read(buffer);
			result = new String(buffer, "UTF-8");
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 读取assets目录的文件内容
	 * 
	 * @param context
	 *            内容上下文
	 * @param fileName
	 *            文件名称,包含扩展名
	 * @return
	 */
	@NonNull
	public static List<String> readAssetsListValue(@NonNull Context context, String fileName) {
		List<String> list = new ArrayList<String>();
		try {
			InputStream in = context.getResources().getAssets().open(fileName);
			BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			String str = null;
			while ((str = br.readLine()) != null) {
				list.add(str);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 获取SharedPreferences文件内容
	 * 
	 * @param context
	 *            上下文
	 * @param fileNameNoExt
	 *            文件名称(不用带后缀名)
	 * @return
	 */
	public static Map<String, ?> readShrePerface(@NonNull Context context, String fileNameNoExt) {
		SharedPreferences preferences = context.getSharedPreferences(
				fileNameNoExt, Context.MODE_PRIVATE);
		return preferences.getAll();
	}

	/**
	 * 写入SharedPreferences文件内容
	 * 
	 * @param context
	 *            上下文
	 * @param fileNameNoExt
	 *            文件名称(不用带后缀名)
	 * @param values
	 *            需要写入的数据Map(String,Boolean,Float,Long,Integer)
	 * @return
	 */
	public static void writeShrePerface(@NonNull Context context, String fileNameNoExt, @NonNull Map<String, ?> values) {
		try {
			SharedPreferences preferences = context.getSharedPreferences(fileNameNoExt, Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = preferences.edit();
			for (Iterator iterator = values.entrySet().iterator(); iterator.hasNext();) 
			{
				Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator.next();
				if (entry.getValue() instanceof String) {
					editor.putString(entry.getKey(), (String) entry.getValue());
				} else if (entry.getValue() instanceof Boolean) {
					editor.putBoolean(entry.getKey(),(Boolean) entry.getValue());
				} else if (entry.getValue() instanceof Float) {
					editor.putFloat(entry.getKey(), (Float) entry.getValue());
				} else if (entry.getValue() instanceof Long) {
					editor.putLong(entry.getKey(), (Long) entry.getValue());
				} else if (entry.getValue() instanceof Integer) {
					editor.putInt(entry.getKey(),(Integer) entry.getValue());
				}
			}
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入应用程序包files目录下文件
	 * 
	 * @param context
	 *            上下文
	 * @param fileName
	 *            文件名称
	 * @param content
	 *            文件内容
	 */
	public static void write(@NonNull Context context, String fileName, @NonNull String content) {
		try {

			FileOutputStream outStream = context.openFileOutput(fileName,
					Context.MODE_PRIVATE);
			outStream.write(content.getBytes());
			outStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入应用程序包files目录下文件
	 * 
	 * @param context
	 *            上下文
	 * @param fileName
	 *            文件名称
	 * @param content
	 *            文件内容
	 */
	public static void write(@NonNull Context context, String fileName, @NonNull byte[] content) {
		try {

			FileOutputStream outStream = context.openFileOutput(fileName,
					Context.MODE_PRIVATE);
			outStream.write(content);
			outStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入应用程序包files目录下文件
	 * 
	 * @param context
	 *            上下文
	 * @param fileName
	 *            文件名称
	 * @param modeType
	 *            文件写入模式(Context.MODE_PRIVATE、Context.MODE_APPEND、Context.
	 *            MODE_WORLD_READABLE、Context.MODE_WORLD_WRITEABLE)
	 * @param content
	 *            文件内容
	 */
	public static void write(@NonNull Context context, String fileName, @NonNull byte[] content,
							 int modeType) {
		try {

			FileOutputStream outStream = context.openFileOutput(fileName,
					modeType);
			outStream.write(content);
			outStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 指定编码将内容写入目标文件
	 * 
	 * @param target
	 *            目标文件
	 * @param content
	 *            文件内容
	 * @param encoding
	 *            写入文件编码
	 * @throws Exception
	 */
	public static void write(@NonNull File target, @NonNull String content, @NonNull String encoding)
			throws IOException {
		BufferedWriter writer = null;
		try {
			if (!target.getParentFile().exists()) {
				target.getParentFile().mkdirs();
			}
			writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(target, false), encoding));
			writer.write(content);

		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
	
	/**
	 * 指定目录写入文件内容
	 * @param filePath 文件路径+文件名
	 * @param content 文件内容
	 * @throws IOException
	 */
	public static void write(@NonNull String filePath, @NonNull byte[] content)
			throws IOException {
		FileOutputStream fos = null;

		try {
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			fos = new FileOutputStream(file);
			fos.write(content);
			fos.flush();
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}
	
	/**
	 * 写入文件
	 * 
	 * @param inputStream下载文件的字节流对象
	 * @param filePath文件的存放路径(带文件名称)
	 * @throws IOException 
	 */
	@NonNull
	public static File write(@NonNull InputStream inputStream, @NonNull String filePath) throws IOException {
		OutputStream outputStream = null;
		// 在指定目录创建一个空文件并获取文件对象
		File mFile = new File(filePath);
		if (!mFile.getParentFile().exists())
			mFile.getParentFile().mkdirs();
		try {
			outputStream = new FileOutputStream(mFile);
			byte buffer[] = new byte[4 * 1024];
			int lenght = 0 ;
			while ((lenght = inputStream.read(buffer)) > 0) {
				outputStream.write(buffer,0,lenght);
			}
			outputStream.flush();
			return mFile;
		} catch (IOException e) {
			Log.e(TAG, "写入文件失败,原因:"+e.getMessage());
			throw e;
		}finally{
			try {
				inputStream.close();
				outputStream.close();
			} catch (IOException e) {
			}
		}
	}
	
	/**
	 * 指定目录写入文件内容
	 * @param filePath 文件路径+文件名
	 * @param content 文件内容
	 * @throws IOException
	 */
	public static void saveAsJPEG(@NonNull Bitmap bitmap, @NonNull String filePath) throws IOException {
		FileOutputStream fos = null;

		try {
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100,fos);
			fos.flush();
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}
	
	/**
	 * 指定目录写入文件内容
	 * @param filePath 文件路径+文件名
	 * @param content 文件内容
	 * @throws IOException
	 */
	public static void saveAsPNG(@NonNull Bitmap bitmap, @NonNull String filePath)
			throws IOException {
		FileOutputStream fos = null;

		try {
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100,fos);
			fos.flush();
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}
}