java文件读写的方法整理

本文演示了Java中使用Scanner、BufferedReader和FileReader进行文件读取,以及使用FileWriter进行文件写入的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下代码的注释内容均为正确内容。




package com.mytest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class FilenameFilterTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
//		//读文件方法1
//			Scanner sc = null;
//			try {
//				sc = new Scanner(new File("C:/Documents and Settings/new/桌面/笔记.txt") );
//				while(sc.hasNextLine())
//				{
//					System.out.println(sc.nextLine());
//				}
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}finally
//			{
//				sc.close();
//			}
		
		 //读文件方法2
//		try {
//			BufferedReader br = new BufferedReader(new FileReader("C:/Documents and Settings/new/桌面/笔记.txt"));
//			String s1 = "";
//			String s2 = "";
//			try {
//				while((s1 = br.readLine()) != null)
//				{
//					s2+=s1+"\n";
//				}
//				br.close();
//				System.out.println(s2);
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		//读文件方法3
//		try {
//			FileReader fr = new FileReader(new File("C:/Documents and Settings/new/桌面/笔记.txt"));
//			int ch ;
//			try {
//				while((ch=fr.read()) != -1)
//				{
//					System.out.print((char)ch);
//				}
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		//写文件方法1
		File file = new File("C:/Documents and Settings/new/桌面/笔记.txt");
		FileWriter fw;
		try {
			//第二个参数为true时,表示追加文件;不写或false时,表示覆盖文件
			fw = new FileWriter(file,false);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter pw = new PrintWriter(bw);
		//	pw.append("keyima");
			pw.print("这是print");
			pw.close();
			bw.close();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值