• java(android)文件处理



    判断外存储设备是否可用:

    public static boolean sdAvailable() {
    		return Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()) || Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    	}
    
    
    
        /** 从assets 文件夹中读取文本数据 */  
           public static String getTextFromAssets(final Context context, String fileName) {  
               String result = "";  
               try {  
                   InputStream in = context.getResources().getAssets().open(fileName);  
                   // 获取文件的字节数  
                   int lenght = in.available();  
                   // 创建byte数组  
                   byte[] buffer = new byte[lenght];  
                   // 将文件中的数据读到byte数组中  
                   in.read(buffer);  
                   result = EncodingUtils.getString(buffer, "UTF-8");  
                   in.close();  
               } catch (Exception e) {  
                   e.printStackTrace();  
               }  
               return result;  
           }  
             
           /** 从assets 文件夹中读取图片 */  
           public static Drawable loadImageFromAsserts(final Context ctx, String fileName) {  
               try {  
                   InputStream is = ctx.getResources().getAssets().open(fileName);  
                   return Drawable.createFromStream(is, null);  
               } catch (IOException e) {  
                   if (e != null) {  
                       e.printStackTrace();  
                   }  
               } catch (OutOfMemoryError e) {  
                   if (e != null) {  
                       e.printStackTrace();  
                   }  
               } catch (Exception e) {  
                   if (e != null) {  
                       e.printStackTrace();  
                   }  
               }  
               return null;  
           }  
    
    从Assert目录复制文件到本地:
        public static boolean copyFileFromAsset(Context mcontext,String destDir,String assetFile){  
                boolean copyok=false;  
                File fdest=new File(destDir);  
                if(!fdest.exists())  
                    fdest.mkdirs();  
                 InputStream is=null;  
                 FileOutputStream fos=null;  
                 byte[] buf=new byte[1024];  
                 int readSize = 0;  
                   
                try {  
                    is = mcontext.getResources().getAssets().open(assetFile);  
                    fos=new FileOutputStream(fdest);  
                    while((readSize = is.read(buf)) > 0){  
                        fos.write(buf, 0, readSize);  
                    }  
                    fos.flush();  
                    copyok=true;  
                } catch (IOException e) {  
                    copyok=false;  
                    e.printStackTrace();  
                }  finally{  
                    if(is!=null)  
                        try {  
                            is.close();  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                    if(fos!=null)  
                        try {  
                            fos.close();  
                        } catch (IOException e) {  
                            e.printStackTrace();  
                        }  
                }  
                return copyok;  
            }  
    
    //文件排序:
    
    public static void sortFilesBySize(File[] files) {
    
    		Arrays.sort(files, new Comparator<File>() {
    			@Override
    			public int compare(File f1, File f2) {
    				if (f1.isDirectory() && f2.isDirectory() || f1.isFile() && f2.isFile())
    					return Long.valueOf(f2.length()).compareTo(f1.length());
    				else if (f1.isDirectory() && f2.isFile())
    					return -1;
    				else
    					return 1;
    			}
    		});
    	}
    
    	public static void sortFilesByName(File[] files) {
    		Arrays.sort(files, new Comparator<File>() {
    			@Override
    			public int compare(File f1, File f2) {
    				if (f1.isDirectory() && f2.isDirectory() || f1.isFile() && f2.isFile())
    					return f1.getName().trim().compareToIgnoreCase(f2.getName().trim());
    				else if (f1.isDirectory() && f2.isFile())
    					return -1;
    				else
    					return 1;
    			}
    		});
    	}
    


    删除指定文件目录,指定文件类型的文件

    public static void deleteDir(File f) {
    		if (f.exists() && f.isDirectory()) {
    			for (File file : f.listFiles()) {
    				if (file.isDirectory())
    					deleteDir(file);
    				file.delete();
    			}
    			f.delete();
    		}
    	}
    
    	public static void deleteDirAllMedias(File f) {
    		if (f != null && f.exists() && f.isDirectory()) {
    			File[] files = f.listFiles();
    			if (files != null) {
    				for (File file : files) {
    					if (file.exists() && !file.isDirectory() && file.canRead() && Media.isVideoOrAudio(file))
    						file.delete();
    				}
    			}
    			files = f.listFiles();
    			if (files == null || files.length == 0)
    				f.delete();
    		}
    	}
    

     
    获取文件名称:

    public static String getFileNameNoEx(String filename) {
    		if ((filename != null) && (filename.length() > 0)) {
    			int dot = filename.lastIndexOf('.');
    			if ((dot > -1) && (dot < (filename.length()))) {
    				return filename.substring(0, dot);
    			}
    		}
    		return filename;
    	}
    
    public static String getUrlFileNameNoEx(String url) {
    		int slashIndex = url.lastIndexOf('/');
    		int dotIndex = url.lastIndexOf('.');
    		String filenameWithoutExtension;
    		if (dotIndex == -1) {
    			filenameWithoutExtension = url.substring(slashIndex + 1);
    		} else {
    			filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
    		}
    		return filenameWithoutExtension;
    	}
    

     
    读取指定文件形成字节流:

    public static final byte[] load(File paramFile) {
    		try {
    			byte[] arrayOfByte = load(new FileInputStream(paramFile));
    			return arrayOfByte;
    		} catch (Exception localException) {
    			Debug.warning(localException);
    		}
    		return new byte[0];
    	}
    
    	public static final byte[] load(FileInputStream paramFileInputStream) {
    		byte[] arrayOfByte = new byte[524288];
    		try {
    			ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    			int j;
    			for (int i = paramFileInputStream.read(arrayOfByte);; i = j) {
    				if (i <= 0) {
    					paramFileInputStream.close();
    					return localByteArrayOutputStream.toByteArray();
    				}
    				localByteArrayOutputStream.write(arrayOfByte, 0, i);
    				j = paramFileInputStream.read(arrayOfByte);
    			}
    		} catch (Exception localException) {
    			Debug.warning(localException);
    		}
    		return new byte[0];
    	}
    

     读取指定文档中内容:

    public static String readFileContent(File paramFile) throws IOException {
    		if (paramFile == null)
    			return null;
    		int i = (int) paramFile.length();
    		byte[] arrayOfByte = new byte[i];
    		FileInputStream localFileInputStream = new FileInputStream(paramFile);
    		int j = localFileInputStream.read(arrayOfByte);
    		String str = null;
    		if (j == i)
    			str = new String(arrayOfByte);
    		localFileInputStream.close();
    		return str;
    	}
    
     public static String readFileContent(File f){
            if(f==null || !f.exists() || !f.isFile())
                return null;
            StringBuilder buf=new StringBuilder();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(f));
                String tmp = null;
                while ((tmp = reader.readLine()) != null) {
                    buf.append(tmp);
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                closeSilently(reader);
            }
            return buf.toString();
        }
    
        public static void closeSilently(Closeable closeable) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (Exception ignored) {
                }
            }
        }
    

    其它形式文件读取

     /**
         * 从assets目录读取文件
         * @param fileName
         * @return
         */
        public String getFromAsset(String fileName,Context mcontext){  
            String result=null;  
            final String ENCODING="UTF-8";
            
            try{  
                InputStream in = mcontext.getResources().getAssets().open(fileName);     //从Assets中的文件获取输入流  
                int length = in.available();                        //获取文件的字节数  
                byte [] buffer = new byte[length];                  //创建byte数组  
                in.read(buffer);                    //将文件中的数据读取到byte数组中  
                result = EncodingUtils.getString(buffer, ENCODING);     //将byte数组转换成指定格式的字符串  
            }  
            catch(IOException e){  
                e.printStackTrace();                        //捕获异常并打印  
            }  
            catch(Exception e){  
                e.printStackTrace();  
            }  
            return result;  
           }  
        
      /**
       * 从resource中的raw文件夹中获取文件并读取数据
       * @param fileName
       * @return
       */
        public String getFromRaw(String fileName,Context mcontext){
        	String result=null;  
            final String ENCODING="UTF-8";
            
            try{
            	InputStream in = mcontext.getResources().openRawResource(R.raw.test1);	//从Resources中raw中的文件获取输入流
            	int length = in.available();					//获取文件的字节数
            	byte [] buffer = new byte[length];				//创建byte数组
            	in.read(buffer);						//将文件中的数据读取到byte数组中
            	result = EncodingUtils.getString(buffer, ENCODING);		//将byte数组转换成指定格式的字符串   
            	in.close();							//关闭输入流
            }
            catch(IOException e){
        		e.printStackTrace();						//捕获异常并打印
        	}
        	catch(Exception e){
        		e.printStackTrace();
        	}
        	return result;
        }
        
      /**
       * 读取项目内部文件
       * @param fileName
       * @param mcontext
       * @return
       */
        public String readFileData(String fileName,Context mcontext){
        	String result=null;  
            final String ENCODING="UTF-8";
            
        	try{
        		FileInputStream fin = mcontext.openFileInput(fileName);//获得FileInputStream对象
        		int length = fin.available();//获取文件长度
        		byte [] buffer = new byte[length];//创建byte数组用于读入数据
        		fin.read(buffer);//将文件内容读入到byte数组中    				
        		result = EncodingUtils.getString(buffer, ENCODING);//将byte数组转换成指定格式的字符串
        		fin.close();					//关闭文件输入流
        	}
        	catch(Exception e){
        		e.printStackTrace();//捕获异常并打印
        	}
        	return result;//返回读到的数据字符串
        }    
     /**
      * 向内部文件写入数据
      * @param filename
      * @param msg
      * @param mcontext
      */
       public void writeData(String filename,String msg,Context mcontext){
        	try {
    			FileOutputStream fos=mcontext.openFileOutput(filename, Context.MODE_PRIVATE);
    			byte[] buf=msg.getBytes();
    			fos.write(buf);
    			fos.close();
    		} catch (FileNotFoundException e) {
    		
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
        }
    

    清空指定文档中的内容:

    public static void delFileContent(File paramFile) throws IOException {
    		if (paramFile == null)
    			return;
    		FileWriter localFileWriter = new FileWriter(paramFile, false);
    		localFileWriter.write("");
    		localFileWriter.close();
    	}
    
     /** 
         * 计算文件或者文件夹的大小 ,单位 MB 
         * @param file 要计算的文件或者文件夹 , 类型:java.io.File 
         * @return 大小,单位:MB 
         */  
        public long getSize(File file) {  
        	long dirSize=0l,fileSize=0l;
            //判断文件是否存在  
            if (file.exists()) {  
                //如果是目录则递归计算其内容的总大小,如果是文件则直接返回其大小  
                if (!file.isFile()) {  
                    //获取文件大小  
                    File[] fl = file.listFiles();  
                    for (File f : fl)  
                    	dirSize += getSize(f);  
                    return dirSize;  
                } else {  
                	fileSize = file.length() / 1024 ;  
             //       System.out.println(file.getName() + " : " + fileSize + "MB");  
                    return fileSize;  
                }  
            } else {  
            //    System.out.println("文件或者文件夹不存在,请检查路径是否正确!");  
                return 0l;  
            }  
    
     
    
    /**
    	 * 文件及文件夹的复制
    	 * 
    	 * @param src
    	 * @param des
    	 * @return
    	 */
    	public static boolean copyFile(String src, String des) {
    
    		File in = new File(src);
    		File out = new File(des);
    		if (!in.exists()) {
    			System.out.println(in.getAbsolutePath() + "源文件路径错误!!!");
    			return false;
    		} else {
    			System.out.println("源文件路径" + in.getAbsolutePath());
    			System.out.println("目标路径" + out.getAbsolutePath());
    
    		}
    		if (!out.exists())
    			out.mkdirs();
    		File[] file = in.listFiles();
    		FileInputStream fin = null;
    		FileOutputStream fout = null;
    		for (int i = 0; i < file.length; i++) {
    			if (file[i].isFile()) {
    				try {
    					fin = new FileInputStream(file[i]);
    				} catch (FileNotFoundException e) {
    					e.printStackTrace();
    				}
    				System.out.println("in.name=" + file[i].getName());
    				try {
    					fout = new FileOutputStream(new File(des + File.separator
    							+ file[i].getName()));
    				} catch (FileNotFoundException e) {
    					e.printStackTrace();
    				}
    				System.out.println(des);
    				int c;
    				byte[] b = new byte[1024];
    				try {
    					while ((c = fin.read(b)) != -1) {
    						fout.write(b, 0, c);
    						System.out.println("复制文件中!");
    					}
    					fin.close();
    					fout.flush();
    					fout.close();
    					System.out.println("复制完毕!");
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			} else
    				copyFile(src + File.separator + file[i].getName(), des
    						+ File.separator + file[i].getName());
    		}
    		return false;
    	}
    
     /**  
         * 文件夹的移动  
         * @param src  
         * @param dest  
         * @return  
         */  
        private static boolean moveFolder(String src, String dest) {  
              File srcFolder = new File(src);  
             File destFolder = new File(dest);  
      
              if(!srcFolder.exists()){  
                  return false;  
              }else{  
                  if(!destFolder.exists())  
                      destFolder.mkdirs();  
                    
                  if(srcFolder.isFile()){  
                      srcFolder.renameTo(new File( dest+srcFolder.getName()));  
                  }  
                  else if(srcFolder.isDirectory()){  
                     File[] files=srcFolder.listFiles();  
                     for(int i=0;i<files.length;i++){  
                         if(files[i].isFile())  
                             files[i].renameTo(new File(dest+File.separator+files[i].getName())); 
                         else  
                             moveFolder(src+File.separator+files[i].getName(), 
                            		 dest+File.separator+files[i].getName());  
                     }  
                  }  
              }  
              return true;  
        }  
    

    高效读取写入操作

    boolean saveFile(Response rsp,File fdest){
    		InputStream in = rsp.body().byteStream();
    		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    		BufferedWriter writer = null;
    		boolean success = false;
    		final int writeLimitSize = 20;
    		
    		try {
    			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fdest)));
    		} catch (FileNotFoundException e1) {
    			e1.printStackTrace();
    			return success;
    		} 
    		
    		String line ;
    		try {
    			while((line = reader.readLine()) != null) {
    //				Pattern p = Pattern.compile("\s*|	|
    |
    ");
    //				Matcher m = p.matcher(line);
    //				String dest = m.replaceAll("");
    				if(0==line.length() || (line.startsWith("	") && line.length() < writeLimitSize) || line.startsWith("
    ")|| line.startsWith("
    "))
    					continue;
    				if(line.length() > writeLimitSize){
    				    writer.write(line);
    				    writer.newLine();
    				}
    			}
    			
    			writer.flush();
    			success = true;
    		} catch (IOException e) {
    			e.printStackTrace();
    		}finally{
    			if(null!=writer){
    				try {
    					writer.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		  
    		return success;
    	}
    
     /**  
         * 获取文件属性  
         * @param path  
         * @param filename  
         */  
        public static void getFile(String path,String filename){  
            File f=new File(path, filename);  
            if(f.exists()){  
                System.out.println("file abspath "+f.getAbsolutePath()+'
    '+"file reable "+f.getParentFile()+'
    '  
                        +"file standar "+f.isFile()+'
    '+"file length "+f.length()+'
    '+"file modify time "+new Date(f.lastModified())+'
    '  
                        +"file can read "+f.canRead()+'
    '+"file can write "  
                        +f.canWrite()+'
    '+"file whether hidden "+f.isHidden());  
            }else{  
                System.out.println("file not exist!");  
            }  
        }  
    
     
    
    /**  
         * 以二叉树形式展示文件名字,(windows文件管理形式)  
         * @param file  
         * @param level  
         */  
        private void treeName(File file,int level){  
            String space= " ";  
            for(int t=0;t<level;t++){  
                space+=" ";  
            }  
            File[] files=file.listFiles();  
            for(int i=0;i<files.length;i++){  
                System.out.println(space+files[i].getName());  
                if(files[i].isDirectory()){  
                    treeName(files[i],level+1);  
                }  
            }  
        }  
        /**
         * 将特定文本信息写入项目所在的根目录下
         * @throws IOException
         */
        public void wrteToProjectFile() throws IOException{
            String str="write dir";  
            
            String filename=System.getProperty("user.dir")+"/src/com/agency/model2/temp.txt";  
            File f=new File(filename);  
            FileWriter fw=new FileWriter(f);  
            fw.write(str);  
            fw.flush();  
            fw.close();  
        }
    

     //java中.properties文件读取方法
    Java中还有一种读取方法通过import java.util.Properties;类来处理
     具体方法如下:
          创建date.properties文件:
         内容如下:
        // num1=10
        //    num2=20
        //    num1=30
        //    注意!在=两边不能用空格否则回报异常,
        //    为方便使用接下来创建一个封装类Myproperties

    class Myproperties {  
            //保持一个实例化对象  
            private static Properties pro=new Properties();  
              
            private Myproperties(){}  
            //当类首次被加载时执行  
            static{  
                try {//加载配置文件信息到内存  
                    pro.load(Myproperties.class.getClassLoader().getResourceAsStream("config/date.properties"));  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            //获取文件内的数据  
            public static String getProperty(String key) {  
                return pro.getProperty(key);  
            }  
        }  
        
        public void readProperty(String filename){
        	//配置文件位置与操作类不在同一包(同一目录)下文件加载
    		BufferedReader br = new BufferedReader(new InputStreamReader(		
    				ReadTxt.class.getClassLoader().getResourceAsStream(filename)));
    		
    		//配置文件位置与操作类在同一包(同一个目录)下面文件加载方式  
    		/*BufferedReader br = new BufferedReader(new InputStreamReader(   
                    ReadTxt.class.getResourceAsStream(filename)));  */
    		
    		String line=null;
    		int row=0;
    		int col=0;
    		try {
    			line = br.readLine();
    			row = Integer.parseInt(line.trim());
    			line = br.readLine();
    			col = Integer.parseInt(line.trim());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		System.out.println(" row= "+row+" col= "+col);
    	}
        //读取测试
        public static void main(String[] args){  
            System.out.println(Myproperties.getProperty("num1"));  
            System.out.println(Myproperties.getProperty("num2"));  
            System.out.println(Myproperties.getProperty("num3"));  
        }  
    





  • 相关阅读:
    蓝牙4.0BLE cc2540 cc2541 ios OAD课程(空中固件升级)[原版的,多图]
    ASP.NET文件上传和下载
    onethink和phpwind共享
    折返(Reentrancy)VS线程安全(Thread safety)
    使用更清晰DebugLog开发和调试工具
    MySql分析算法作品索引(马上,只是说说而已B-tree)
    使用shell命令分析统计日志
    刷牙LeetCode思考
    Cocos3d-x 发布第一版
    SSH连接Linux的Server超时
  • 原文地址:https://www.cnblogs.com/happyxiaoyu02/p/6818954.html
Copyright © 2020-2023  润新知