欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现读取txt文件并以在每行以空格取数据

程序员文章站 2024-02-18 23:45:04
简单一个例子。其中正则是取消多余空格或者tab键 package test4; import java.io.bufferedreader; impor...

简单一个例子。其中正则是取消多余空格或者tab键

package test4;
 
import java.io.bufferedreader;
import java.io.filereader;
import java.io.ioexception;
 
public class explacesql {
	public static void main(string[] args) {
		 string filepath = explacesql.class.getresource("").getpath()+"aaa.txt"; // 文件路径
		 read(filepath);
	}
	
	/**
	 * 读取内容
	 */
	public static string read(string filepath){
		bufferedreader br = null;
		string line =null;
		//stringbuffer buf = new stringbuffer();
		try {
			//根据文件路径创建缓冲输入流
			br = new bufferedreader(new filereader(filepath));//filepath中是aaa.txt文件
			string str = "";
			
			//循环读取文件的每一行,对需要修改的行进行修改,放入缓冲对象中
			 while ((line = br.readline()) != null) {
				 //设置正则将多余空格都转为一个空格
				 str=line+"\r\n";
				 string[] dictionary = str.split("\\s{2,}|\t");
				 for(int i=0;i<dictionary.length;i++){
					str = "insert into tablename values("+ dictionary[0]+",'"+dictionary[1]+"',"+dictionary[2]+"')";
				 }
				 system.out.println(str);
				 
			 }
		} catch (exception e) {
			e.printstacktrace();
		}finally {
	   if (br != null) {// 关闭流
	    try {
	     br.close();
	    } catch (ioexception e) {
	      br = null;
		  }
		  }
		}
		return null;
	}
	
}

java逐行读写txt文件

package help;
 
import java.io.bufferedreader;
import java.io.bufferedwriter;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.inputstreamreader;
import java.io.outputstreamwriter;
import java.util.hashmap;
import java.util.map;
 
public class txtparseutils {
 
 private static final integer one = 1;
 
 public static void main(string[] args) {
  map<string, integer> map = new hashmap<string, integer>();
 
  /* 读取数据 */
  try {
   bufferedreader br = new bufferedreader(new inputstreamreader(new fileinputstream(new file("d:/报销.txt")),
                   "utf-8"));
   string linetxt = null;
   while ((linetxt = br.readline()) != null) {
    string[] names = linetxt.split(",");
    for (string name : names) {
     if (map.keyset().contains(name)) {
      map.put(name, (map.get(name) + one));
     } else {
      map.put(name, one);
     }
    }
   }
   br.close();
  } catch (exception e) {
   system.err.println("read errors :" + e);
  }
 
  /* 输出数据 */
  try {
   bufferedwriter bw = new bufferedwriter(new outputstreamwriter(new fileoutputstream(new file("d:/结果.txt")),
                   "utf-8"));
 
   for (string name : map.keyset()) {
    bw.write(name + " " + map.get(name));
    bw.newline();
   }
   bw.close();
  } catch (exception e) {
   system.err.println("write errors :" + e);
  }
 }
}

以上这篇java实现读取txt文件并以在每行以空格取数据就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。