Java文件处理基础

目录

1.file对象常用方法

2.使用Scanner对象读取文件内容

2.1异常处理

 2.2基于标记的文件处理

2.3基于行的处理

 2.4读取字符串与基于行基于标记处理方式的混合应用

3.高级文件处理

3.1 使用PrintStream输出文件内容

3.2 保证文件可读 


1.file对象常用方法

import java.io.*;    // for file

public class File_processing {
	
	public static void main(String[] args) {
		
		File f = new File("lover.txt");   // 提供文件名创建对应的File对象(注意不是创建新的文件)
		System.out.println(f.exists());   // 判断当前文件是否存在
		System.out.println(f.canRead());   // 判断当前文件是否存在且可读
		System.out.println(f.getAbsolutePath());   // 获取当前文件的绝对路径
		System.out.println(f.getName());   // 获取当前文件名称,不含任何路径内容
		System.out.println(f.isDirectory());  //  判断当前文件是否为目录/文件夹
		System.out.println(f.isFile());   //  判断当前文件是否为文件
		System.out.println(f.length());   //  获取文件中包含的字符数量
		f.delete();   //  删除当前文件
		
	}

}

2.使用Scanner对象读取文件内容

2.1异常处理

1.FileNotFoundException异常

Scanner input = new Scanner(new File("puppy.txt"));

处理方法如下:

import java.util.*;
import java.io.*;    // for file

//  这段程序用于统计文档《puppy》中出现的单词数
public class File_processing {
	
	public static void main(String[] args) 
	throws FileNotFoundException  {  // 注意花括号的位置
		Scanner input = new Scanner(new File("puppy.txt"));
		int count = 0;
		while (input.hasNext()) {
			String word = input.next();
			count++;
		}
		System.out.println("total words = " + count);
	}
}

2.NoSuchElementException异常 

 在之前的while循环后中我们加入一行String extra = input.next(); 运行后会发现程序抛出异常,这是因为文件已经读到末尾,没有内容可以再被读取了

import java.util.*;
import java.io.*;    // for file

public class File_processing {
	
	public static void main(String[] args) 
	throws FileNotFoundException  {  // 注意花括号的位置
		Scanner input = new Scanner(new File("puppy.txt"));
		int count = 0;
		while (input.hasNext()) {
			String word = input.next();
			count++;
		}
		String extra = input.next();   // illegal,no more input
		System.out.println("total words = " + count);
	}
}

 

 2.2基于标记的文件处理

Scanner类提供的基于标记的文件处理方法
nextInt读取下一个int类型的值
nextDouble读取下一个double类型的值
next读取下一个标记,并保存为string对象
import java.util.*;
import java.io.*;    

public class File_processing {
	
	
	public static void main(String[] args) 
	throws FileNotFoundException  { 
		Scanner input = new Scanner(new File("number.txt"));
		
		double sum = 0;
		int count = 0;
		while(input.hasNextDouble()) {   // 用while循环读出所有的数值,用hasNextDouble判断是否有一个double类型可读
			double next = input.nextDouble();
			count++;
			System.out.println("number " + count + " = " + next);
			sum += next;
		}
		
		System.out.println("sum = " + sum);
	}
}

 但是,如果文件中除了double类型还包含其他类型的数据,那么在运行上述程序的时候就会报错,Scanner会抛出InputMismathException异常。
     * 在处理文件时,Scanner对象保存文件当前位置的信息,可以将其理解为一个输入指针(指向输入文件当前位置的指针)
     * 输入指针会随着输入各种next信息向前移动,称为处理输入
     * 当把输入指针作为参数传递给某种方法的时候,其中的输入指针并不会自动复位到文件的开头位置
  示例程序如下:

import java.util.*;
import java.io.*;    

public class File_processing {
	/*
	 * 在处理文件时,Scanner对象保存文件当前位置的信息,可以将其理解为一个输入指针(指向输入文件当前位置的指针)
	 * 输入指针会随着输入各种next信息向前移动,称为处理输入
	 * 当把输入指针作为参数传递给某种方法的时候,其中的输入指针并不会自动复位到文件的开头位置
	 */
	
	public static void main(String[] args) 
	throws FileNotFoundException  { 
		Scanner input = new Scanner(new File("number.txt"));
		processTokens(input,2);	
		processTokens(input,4);	
		processTokens(input,2);	
	}
	
	public static void processTokens(Scanner input,int n) {
		double sum = 0;
		for (int i = 1;i <= n;i++) {
			double next = input.nextDouble();
			System.out.println("number " + i + " = " + next);
			sum += next;
		}
		System.out.println("sum = " + sum);
		System.out.println();
	}
}

2.3基于行的处理

利用循环逐行读入文件,直到读完所有行为止,示例程序如下:

import java.util.*;
import java.io.*;    

public class File_processing {
	public static void main(String[] args) 
	throws FileNotFoundException  {   
		Scanner input = new Scanner(new File("puppy.txt"));
		while(input.hasNextLine()) {
			String text = input.nextLine();
			System.out.println(text.toUpperCase());
		}
	}
}

 输出结果:

 2.4读取字符串与基于行基于标记处理方式的混合应用

// 举例:计算公司员工工作时间的总数
// 处理思路:嵌套循环——外层循环每次处理一个员工的信息,内层循环每次处理一个数值,计算累加和

import java.util.*;
import java.io.*;    

public class File_processing {
	
	public static void main(String[] args) 
	throws FileNotFoundException  {                                
		// 在main方法的头部需要添加throws FileNotFoundException语句,但在process方法中不用添加,因为打开文件的操作是在main方法里完成的
		Scanner input = new Scanner(new File("Hoursworked.txt"));
		process(input);	
	}
	
	public static void process(Scanner input) {
		while(input.hasNext()) {   
			String name = input.next();
			double sum = 0.0;
			while(input.hasNextDouble()) {
				sum += input.nextDouble();
			}
		System.out.println("Thtal hours worked by " + name + " = " + sum);
		}
		
	}
}

 如果我们对文件的格式稍作调整,在人名前加上编号,又应该怎么处理呢?

 我们需要在while循环里加上一句int id = input.nextInt();并且让程序逐行读入员工的信息

import java.util.*;
import java.io.*;    

public class File_processing {
	public static void main(String[] args) 
	throws FileNotFoundException  {                                
		// 在main方法的头部需要添加throws FileNotFoundException语句,但在process方法中不用添加,因为打开文件的操作是在main方法里完成的
		Scanner input = new Scanner(new File("HoursWorked.txt"));
		while (input.hasNextLine()) {
			String text = input.nextLine();
			processLine(text);
		}
	}
	
	public static void processLine(String text) {
		Scanner data = new Scanner(text);
		int id = data.nextInt();
		String name = data.next();
		double sum = 0.0;
			while(data.hasNextDouble()) {
				sum += data.nextDouble();
			}
		System.out.println("Thtal hours worked by " + name + "(id#"+ id +")"+ " = " + sum);
				
	}
}

输出结果:

3.高级文件处理

3.1 使用PrintStream输出文件内容

创建PrintStream对象

PrintStream output = new PrintStream(new File("puppy.txt"));

 若指定的输出文件不存在,程序会自动创建它。如果文件存在,程序会删除原有内容后写入新的内容。

在创建了PrintStream对象之后,需要调用output.print()和output.println()

举一个简单的例子:

import java.util.*;
import java.io.*;    

public class File_processing {
	public static void main(String[] args) 
	throws FileNotFoundException  {                                
		PrintStream output = new PrintStream(new File("Hello.txt"));
		output.println("Hello,world!");
		output.println();
		output.println("The programe produces three lines of output.");		
	}
}

运行后控制台并没有输出信息,但所有输出信息都被保存到"Hello.txt"文件中 

 再举一个例子,假如下面有这样一个文件"puppy.txt",要删除其中多余的空格,将输出结果保存在"Hello.txt"中。

 代码实现如下:

import java.util.*;
import java.io.*;    

public class File_processing {
	public static void main(String[] args) 
	throws FileNotFoundException  {                                
		Scanner input = new Scanner(new File("puppy.txt"));
		PrintStream output = new PrintStream(new File("Hello.txt"));
		while(input.hasNextLine()) {
			String text = input.nextLine();
			echoFixed(text,output);
			echoFixed(text,System.out);
		}
	}
	
	public static void echoFixed(String text,PrintStream output) {
		Scanner data = new Scanner(text);
		if (data.hasNext()) {
			output.print(data.next());
			while(data.hasNext()) {
				output.print(" "+data.next());
			}
		}
	    output.println();
	}

运行结果:

3.2 保证文件可读 

通用代码:不需要修改就可以应用到其它程序中的代码(如下方示例中的getInput方法)

import java.util.*;
import java.io.*;    

public class File_processing {
	public static void main(String[] args) 
	throws FileNotFoundException  {                                
		Scanner console = new Scanner(System.in);
		Scanner input = getInput(console);
		// 用此程序计算用户输入文件中的字数
		int count = 0;
		while(input.hasNext()) {
			String word = input.next();
			count++;
		}
		System.out.println("文件总字数为"+count);	
	}

	
	public static Scanner getInput(Scanner console) 
	throws FileNotFoundException {
		System.out.print("请输入文件名");
		File f = new File(console.nextLine());
		while(!f.canRead()) {             // File类提供CanRead方法测试指定文件是否存在且可读
			System.out.println("该文件不存在,请重新输入");
			System.out.print("请输入文件名");
			f = new File(console.nextLine());
		}
		return new Scanner(f);
	}	
}

运行结果:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

N._

piu~打个赏吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值