Java操作TXT文件详解(文件读取)

TXT文件编码与读取优化
本文介绍如何高效地读取TXT文件,并提供了一个方法来获取文件编码,以确保跨平台兼容性。此外,通过实例展示了如何计算文件行数及以制表符分隔的方式读取文件信息。

 

        单单读取TXT文件的话,用BufferedReader效率比较高,也方便一些。需要注意的是,TXT文件在不同版本的操作系统中编码格式会有所不同,笔者曾经试过在两台同样的WIN7系统下,一个格式为“UTF-8”,一个格式为“GB2312”。所以在操作TXT文件之前,最好先确认一下该TXT文件的编码格式。

 


 

private String GetTxtCode(String path) // 获取text文件编码
	{
		String code = "";
		code = "gb2312";
		try {
			InputStream is = new FileInputStream(path);
			byte[] head = new byte[3];
			try {
				is.read(head);

				if (head[0] == -1 && head[1] == -2)
					code = "UTF-16";
				if (head[0] == -2 && head[1] == -1)
					code = "Unicode";
				if (head[0] == -17 && head[1] == -69 && head[2] == -65)
					code = "UTF-8";
			} catch (IOException e) {

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

			e.printStackTrace();
		}

		return code;
	}


 

此时我们就可以将FileCode传入FileInputStream安全打开TXT文件。如果使用二维数组作为返回值读取文件的话,我们最好先读取文件行数以定义数组维度,方法示例如下:

 

 

public int GetLines(String fileName) throws IOException //获取文件行数以便建立数组维度
	{
		FileReader in = new FileReader(fileName);
        LineNumberReader reader = new LineNumberReader(in);
        String strLine = reader.readLine();
        int totalLines = 0;
        while (strLine != null) {
            totalLines++;
            strLine = reader.readLine();
        }
        reader.close();
        in.close();
        return totalLines;

	}



然后读取文件信息,这里读取的文件每行四个信息块,以制表符为分隔符:

 

public String [][] GetInfo(String path) throws IOException, FileNotFoundException{
		
		int Lines=this.GetLines(path);
		String [][] s = new String[Lines][4];
     		File f = new File(path);
		
		String code = GetTxtCode(path);
//		System.out.println("Txt File Code:" + code);
		if (f.isFile() && f.exists()) {
			InputStreamReader sr = new InputStreamReader(
					new FileInputStream(f), code);
			BufferedReader bf = new BufferedReader(sr);
//			bf.skip(1);
			String line;
			String[] lin=new String[4];
			int i=0;
			while ((line = bf.readLine()) != null) {
				lin = line.split("	");
				
				s[i][0]=lin[0];
				s[i][1]=lin[1];
				s[i][2]=lin[2];
				s[i][3]=lin[3];
				i++;
				
			}
			
		
		}
		return s;
	}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值