Java与Android的文件读写操作

Java之文件的读写操作

package com.example;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;;

public class MainActivity {
   public static void main (String[] args){
       try{
           /* 读入文件内容 */
           String pathname = "C:\\Users\\lzl\\Desktop\\aa.txt"; //获取文件的绝对路径
           File filename = new File(pathname);
           InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
           BufferedReader br = new BufferedReader(reader);
           String line = "";
           while((line = br.readLine()) != null){     //一次读入一行,判断条件很关键
               System.out.println(line);
           }

           /* 写入文件内容 */
           File file = new File("C:\\Users\\lzl\\Desktop\\bb.txt");
           file.createNewFile();
           BufferedWriter bw = new BufferedWriter(new FileWriter(file)); //
           bw.write("test\r\ntest\r\n");  //\r\n即为换行
           bw.flush();  //把缓存区的内容转到文件中
           bw.close();

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

注意在读取文件中的内容时当采用以下方法会导致不能读取文件中的最后一行。

           line = br.readLine();
           while(line != null){
               line = br.readLine();
               System.out.println(line);
           }

Android之文件读写操作

Android之文件读操作
public String load(){
    FileInputStream in = null;
    BufferedReadr br = null;
    StringBuilder content = new StringBuilder();
    try{
        in = openFileStream("XX");  //读取文件
        br = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while((line = br.readline()) != null){  //这条与语句很重要
          content.append(line);
        }
      }catch(IOException e){
          e.printStackTrace();
      } finally{
           try{
                if(bw != null){
                  br.close();
                }
           }catch(IOException e){
                e.printStackTrace();
              }
            }
      return content.toString();
}
Android之文件写操作
public void  save(){
    String data = "XX";
    FileOutputStream fos = null;
    try{
        fos = openFileOutput("data" , Context.MODE_PRIVATE);
        OutputStreamWriter out = new OutputStreamWriter(fos);
        BufferedWiter bw = new BufferedWriter(out);
        bw.write(data);
    }catch(IOException e){
        e.printStackTrace();
    } finally{
        try{
            if(bw != null){
              br.close();
            }
        }catch(IOException e){
            e.printStackTrace();
          }
        }

}

关键的区别在于,Android的自己的文件存储位置,通过openFileStream自动的定位,而Java中是通过pathname来获取绝对路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值