java关于文件读写和复制

复制文件两种方式

1.以字符的形式+缓冲

 File file1=new File("E:/Student.txt");
		File file2=new File("E:/TEST.txt");
		try
		{
    
    
			FileReader fr=new FileReader(file2);
			FileWriter fw=new FileWriter(file1);
			BufferedReader br=new BufferedReader(fr);
			BufferedWriter bw=new BufferedWriter(fw);
			
			char c[]=new char[1000];
			int len=0;
			while((len=br.read(c))!=-1)
			{
    
    
				
				bw.write(c,0,len);
			}
			bw.flush();
			bw.close();
			br.close();
			fr.close();
			fw.close();

2.以字节的形式(流)

File file1=new File("E:/Student.txt");
		File file2=new File("E:/TEST.txt");
		try
		{
    
    
			FileOutputStream out=new FileOutputStream(file1);
			FileInputStream in=new FileInputStream(file2);
			byte b[]=new byte[1000];
			int len=0;
			while((len=in.read(b))!=-1)
			{
    
    
				out.write(b,0,len);
			}
			out.flush();
			out.close();
			in.close();
			
		} catch (Exception e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

读写文件

public static File file=new File("E:/Student.txt");
	//将用户输入的信息写入到txt中
	public static void PutIn()
	{
    
    
		Scanner cin=new Scanner(System.in);
		System.out.println("请输入您要添加的学生数量:");
		int n=cin.nextInt();
		System.out.println("请依次输入学生姓名   数学  物理  化学");
		
		try {
    
    
			FileWriter fw=new FileWriter(file);
			BufferedWriter bw=new BufferedWriter(fw);
			bw.write("姓名"+"  "+"数学"+"  "+"物理"+" "+"化学"+"\n");
			bw.flush();
			for(int i=0;i<n;i++)
			{
    
    
				String name;
				int math,phy,che;
				name=cin.next();
				math=cin.nextInt();
				phy=cin.nextInt();
				che=cin.nextInt();
				bw.write(name+"   "+math+"   "+phy+"   "+che+"\n");
				bw.flush();
			}
			bw.close();fw.close();
		} catch (Exception e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void read()
	{
    
    
		List<Student>list=new ArrayList();
		try {
    
    
			FileReader fr=new FileReader(file);
			BufferedReader br=new BufferedReader(fr);
			String k;
			k=br.readLine();
			while((k=br.readLine())!=null)
			{
    
    
				String s[]=k.split("   ");
				list.add(new Student(s));
			}
		} catch (Exception e) 
		{
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (Student student : list) 
		{
    
    
			System.out.println(student);
		}
	}

猜你喜欢

转载自blog.csdn.net/weixin_45988242/article/details/111359010