JAVA之字符流和文件的常见操作

THE ONE 

 定义一个集合,向集合中添加一些字符串,然后将集合中的所有字符串内容写到文件中,每个字符串占一行。

 
分析:
   1, 定义一个集合ArrayList,
   2. add添加字符串
   3. 定义字符流缓冲对象 BufferedWriter

   4. 循环遍历集合写入文件,注意换行

          代码:

public static void main(String[] args) throws IOException {
		ArrayList<String> arrayList=new ArrayList<String>();
		arrayList.add("1:你好");
		arrayList.add("2:你不好");
		arrayList.add("3:你非常不好");
		
		BufferedWriter bw=new BufferedWriter(new FileWriter("test1.txt"));
		
		for (String arr : arrayList) {
			bw.write(arr);
			bw.newLine();
		}
		bw.close();	

	}

THE TWO     

将文件中的字符串文本读取到集合当中,并且每一行文本作为集合中的一个元素

            代码:

public static void main(String[] args) throws IOException {
		FileReader fr=new FileReader("test1.txt");
		BufferedReader bfr=new BufferedReader(fr);
		
		String line;
		ArrayList<String> arrayList =new ArrayList<String>();
		while ((line=bfr.readLine())!=null) {
			arrayList.add(line);
		}
		for (String string : arrayList) {
			System.out.println(string);
		}
	}

THE THREE

将一个文本文档上的文本反转,第一行和倒数第一行交换,第二行和倒数第二行交换

            分析:

              1,创建输入输出流对象
      2,创建集合对象
      3,将读到的数据存储在集合中
      4,倒着遍历集合将数据写到文件上
      5,关流 

            代码:

public static void main(String[] args) throws IOException {
		
		 
		 ArrayList<String > arrayList=new ArrayList<String>();
		 
		 FileReader fr=new FileReader("test1.txt");
		 BufferedReader bfr=new BufferedReader(fr);
		 
		 String line;
		 
		 FileWriter fw=new FileWriter("test3.txt");
		 BufferedWriter bfw=new BufferedWriter(fw);
		 
		 while ((line=bfr.readLine())!=null) {
			 arrayList.add(line);
		}
		for (int i = arrayList.size()-1;i>=0; i--) {
			 String line1=arrayList.get(i); 
			 bfw.write(line1);
			 bfw.newLine();
		}
		bfw.close();
		bfr.close();
		 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值