首页 > 其他分享 >在Android中实现文件读写

在Android中实现文件读写

时间:2023-05-01 14:08:52浏览次数:43  
标签:Toast 文件 String isr 读写 context close new Android


android 实现下载文件

/**

  * 从网上下载

  *@param url 下载路径

  *@param outputFile 创建本地保存流的文件

  *@return

  * @return 下载失败返回1(比如没有网络等情况)下载成功返回0

  */

  public static int downloadFile(String urlPsth, File outputFile) {

  int result=0;

  try {

  URL url = new URL(urlPsth);

  HttpURLConnection conn =(HttpURLConnection) url.openConnection();

  conn.setDoInput(true);

  conn.connect();

  if( conn.getResponseCode() == HttpURLConnection.HTTP_OK)

  {

  InputStream is = conn.getInputStream();

  FileOutputStream fos = new FileOutputStream(outputFile);

  byte[] bt = new byte[1024];

  int i = 0;

  while ((i = is.read(bt)) > 0) {

  fos.write(bt, 0, i);

  }

  fos.flush();

  fos.close();

  is.close();

  }else {

  result=1;

  }

  } catch (FileNotFoundException e) {

  result=1;

  } catch (IOException e) {

  result=1;

  }

  return result;

  }




编程中文件读写是少不了的,如下:



读:


public String ReadSettings(Context context){ 

      FileInputStream fIn = null; 

      InputStreamReader isr = null; 

      

      char[] inputBuffer = new char[255]; 

      String data = null; 

      

      try{ 

       fIn = openFileInput("settings.dat");       

          isr = new InputStreamReader(fIn); 

          isr.read(inputBuffer); 

          data = new String(inputBuffer); 

          Toast.makeText(context, "Settings read",Toast.LENGTH_SHORT).show(); 

          } 

          catch (Exception e) {       

          e.printStackTrace(); 

          Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show(); 

          } 

          finally { 

             try { 

                    isr.close(); 

                    fIn.close(); 

                    } catch (IOException e) { 

                    e.printStackTrace(); 

                    } 

          } 

          return data; 

     }


写:


public void WriteSettings(Context context, String data){ 

      FileOutputStream fOut = null; 

      OutputStreamWriter osw = null; 

      

      try{ 

       fOut = openFileOutput("settings.dat",MODE_PRIVATE);       

          osw = new OutputStreamWriter(fOut); 

          osw.write(data); 

          osw.flush(); 

          Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show(); 

          } 

          catch (Exception e) {       

          e.printStackTrace(); 

          Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show(); 

          } 

          finally { 

             try { 

                    osw.close(); 

                    fOut.close(); 

                    } catch (IOException e) { 

                    e.printStackTrace(); 

                    } 

          } 

     }

使用方法:

WriteSettings(this,"setting0, setting1, setting2"); 

String data[] = ReadSettings(this).split(",");



在读取txt文件时,可能会遇到中文乱码情况,解决办法如下:


private String getTextString(String pathandname) throws IOException{
		
		String str="";
		
		FileInputStream fis = new FileInputStream(pathandname);
//		InputStreamReader isr=new InputStreamReader(fis, "gbk");
//		BufferedReader br=new BufferedReader(isr);
		
		int size=fis.available();
		
		byte[] buffer=new byte[size];
		
		fis.read(buffer);

		fis.close();
		   
		str = new String(buffer,"GBK");//支持双字节字符
		
		myApp.setCharNumofString(str.length());//存储总字符数
		
		return  str;
	}



读取assets文件夹下的txt文件


http://gundumw100.iteye.com/blog/850611


标签:Toast,文件,String,isr,读写,context,close,new,Android
From: https://blog.51cto.com/u_5454003/6238856

相关文章

  • android DragLayer源码
    Android_launcher的源码详细分析/**Copyright(C)2008TheAndroidOpenSourceProject**LicensedundertheApacheLicense,Version2.0(the"License");*youmaynotusethisfileexceptincompliancewiththeLicense.*......
  • Android提高第十五篇之ListView自适应实现表格
    上次介绍了使用GridView实现表格,这次就说说如何用ListView实现自适应的表格。GridView比ListView更容易实现自适应的表格,但是GridView每个格单元的大小固定,而ListView实现的表格可以自定义每个格单元的大小,但因此实现自适应表格也会复杂些(格单元大小不一)。......
  • Android提高第八篇之SQLite分页读取
    Android包含了常用于嵌入式系统的SQLite,免去了开发者自己移植安装的功夫。SQLite支持多数SQL92标准,很多常用的SQL命令都能在SQLite上面使用,除此之外Android还提供了一系列自定义的方法去简化对SQLite数据库的操作。不过有跨平台需求的程序就建议使用标准的SQL语句,毕竟这样容易在......
  • Android提高第九篇之GridView和SQLite实现分页表格
    上次讲的Android上的SQLite分页读取,只用文本框显示数据而已,这次就讲得更加深入些,实现并封装一个SQL分页表格控件,不仅支持分页还是以表格的形式展示数据。先来看看本文程序运行的动画:这个SQL分页表格控件主要分为“表格区”和“分页栏”这两部分,这两部分都是基于GridView实现的。......
  • Android提高第四篇之Activity+Intent
          Android有三个基础组件Activity,Service和BroadcastReceiver,他们都是依赖Intent来启动。本文介绍的是Activity的生命周期以及针对Activity的Intent使用。       之前的例子一直都是使用Activity,在一个LayoutXML与一个Activity捆绑的情况下可以视为一个Form,......
  • Android提高第十八篇之自定义PopupWindow实现的Menu(TabMenu)
    用过UCWEB-Android版的人都应该对其特殊的menu有印象,把menu做成Tab-Menu(支持分页的Menu),可以容纳比Android传统的menu更丰富的内容(Android的menu超过6项则缩略在[更多]里),本文参考网上的例子(作者:CoffeeCole,email:[email protected]),对例子进行简化以及封装,使其作为一个复......
  • Android Activity界面切换添加动画特效
    在Android2.0之后有了overridePendingTransition(),其中里面两个参数,一个是前一个activity的退出两一个activity的进入。@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentVi......
  • vscode配置文件
    vscode用户配置文件{/*editor*/"editor.cursorBlinking":"smooth",//使编辑器光标的闪烁平滑,有呼吸感"editor.formatOnPaste":true,//在粘贴时格式化代码"editor.formatOnType":true,//敲完一行代码自动格式化"editor.smoothScrolling"......
  • android系统各种音量的获取与设置 以及监听音量变化
    获取系统音量通过程序获取android系统手机的铃声和音量。同样,设置铃声和音量的方法也很简单!设置音量的方法也很简单,AudioManager提供了方法:publicvoidsetStreamVolume(intstreamType,intindex,intflags)其中streamType有内置的常量,去文档里面就可以看到。JAVA代码:AudioManagermAud......
  • 电脑上的linux是什么文件夹,Windows中现在有独立的Linux文件夹系统
    三月中旬,微软曾通过博客宣布,WSL2将在Windows102004版本中正式进入普遍可用(GA,GenerallyAvailable)状态。与此同时,微软表示对WSL2所依赖的 Linux 内核的提供方式也会进行一些改进。随着Windows10InsiderBuilt19603版本(即Windows102004预览版)的到来,微软又为......