需要读取的.txt文本
读取后的.txt文本
求代码,谢谢各位大佬
public static void main(String[] args) throws Exception {
File file = new File("readFilePath");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("outFilePath")),"UTF-8"));
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream),5*1024*1024);
String line = null;
if((line = reader.readLine()) != null) {
String[] infoArraay = line.split("\t");
writer.write(infoArraay[0]+"\t"+infoArraay[1]);
writer.newLine();
}
while((line = reader.readLine()) != null) {//逐行的读
String[] infoArraay = line.split("\t");
writer.write(infoArraay[0]+","+infoArraay[1]);
writer.newLine();
}
reader.close();
writer.close();
}
你后一个txt 里 ab中间变空格了?之前是制表符?还是我看错了
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\BordersMoved\\Desktop\\a.txt");
BufferedReader bf = new BufferedReader(new FileReader(f));
String str;
int count = 0;
String ab = "";
while ((str = bf.readLine()) != null) {
if (0 == count) {
ab += str + "\r\n";
} else {
String[] s = str.split(" ");
for (int i = 0; i < s.length; i++) {
if (i == s.length - 1) {
ab += s[i] + "\r\n";
} else {
ab += s[i] + ",";
}
}
}
count++;
}
bf.close();
System.out.print(ab);
// ab写入文件
writeTxtFile(ab, new File("C:\\Users\\BordersMoved\\Desktop\\b.txt"));
}
public static boolean writeTxtFile(String content, File fileName) throws IOException {
RandomAccessFile mm = null;
boolean flag = false;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(content.getBytes("gbk"));
fileOutputStream.close();
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
你看下
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* 问题描述:
* 一个文本文件,第一行是标签,剩下是数据,使用空白字符分割
* 将该文件迁移到其他文件中
*
* @author xuanchi.lyf
*/
public class LabeledFileTransform {
/**
* 当前文件的分隔符
*/
private String currentSplitter;
/**
* 迁移之后的分隔符
*/
private String transformSplitter;
/**
* 需要被迁移的字段
*/
private Set<String> transformLabelSet;
public LabeledFileTransform(String currentSplitter, String transformSplitter, Set<String> transformLabelSet) {
this.currentSplitter = currentSplitter;
this.transformSplitter = transformSplitter;
this.transformLabelSet = transformLabelSet;
}
/**
* 迁移数据
*
* @param filePath 文件
* @param targetFilePath 目标文件
*/
public void transform(String filePath, String targetFilePath) {
BufferedReader bufferedReader = null;
FileOutputStream fileOutputStream = null;
try {
bufferedReader = new BufferedReader(new BufferedReader(new FileReader(filePath)));
fileOutputStream = new FileOutputStream(targetFilePath);
boolean first = true;
String[] labelList = null;
boolean[] writeFlags = null;
List<String> buffer = Lists.newArrayList();
String line;
while ((line = bufferedReader.readLine()) != null) {
// 处理label
if (first) {
labelList = line.split(currentSplitter);
writeFlags = new boolean[labelList.length];
for (int i = 0; i < labelList.length; i++) {
writeFlags[i] = transformLabelSet.contains(labelList[i]);
}
first = false;
}
// 处理数据
buffer.clear();
Joiner joiner = Joiner.on(transformSplitter);
String[] data = line.split(currentSplitter);
for (int i = 0; i < data.length; i++) {
if (writeFlags[i]) {
buffer.add(data[i]);
}
}
fileOutputStream.write(joiner.join(buffer).getBytes());
fileOutputStream.write(System.getProperty("line.separator").getBytes());
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 测试
*/
public static void main(String[] args) {
String currentSplitter = "\\s+";
String transformSplitter = ",";
Set<String> transformLabelSet = Sets.newHashSet("a", "b", "c");
LabeledFileTransform labeledFileTransform = new LabeledFileTransform(currentSplitter, transformSplitter, Sets.newHashSet(transformLabelSet));
String filePath = "/Users/xuanchi.lyf/Desktop/test.txt";
String targetFilePath = "/Users/xuanchi.lyf/Desktop/test-transform.txt";
labeledFileTransform.transform(filePath, targetFilePath);
}
}
需要依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>17.0</version>
</dependency>
http://mvnrepository.com/artifact/com.google.guava/guava/17.0
import java.io.BufferedInputStream;
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;
public class TestAAA {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\Administrator\\Desktop\\新建文本文档.txt");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\新建文本文档1.txt")),"UTF-8"));
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream),5*1024*1024);
String line = null;
if((line = reader.readLine()) != null) {
String[] infoArraay = line.split("\t");
writer.write(infoArraay[0]+"\t"+infoArraay[1]);
writer.newLine();
}
while((line = reader.readLine()) != null) {//逐行的读
String[] infoArraay = line.split("\t");
writer.write(infoArraay[0]+","+infoArraay[1]);
writer.newLine();
}
reader.close();
writer.close();
}
}
上面是代码,下面是txt的,本地运行过
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ReadText {
public static List<TxtRow> readFileByLines(String fileName) {
//File file = new File(fileName);
List<TxtRow> list = new ArrayList<>();
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
System.out.println("line " + line + ": " + tempString);
tempString.trim(); //清空首尾的空格
/*System.out.println("-------------只有一个间隔--------------------");
String [] strs = tempString.split(" "); //第一次分割是还没有替换空格的,和下边做对比
for(int i=0;i<strs.length;i++) {
System.out.println(strs[i]);
}*/
System.out.println("-------------间隔不固定--------------------");
String string = tempString.replaceAll(" {1,}", " "); //替换多个空格
String [] strs2 = string.split(" "); //以空格作为分割,打印输出,注意txt中不要出现tab打出来的缩进空格
TxtRow txtRow = new TxtRow();
for(int i=0;i<strs2.length;i++) {
System.out.println(strs2[i]);
if(i==0){
txtRow.setFirst(strs2[i]);
}else if(i==1){
txtRow.setSecond(strs2[i]);
}
}
list.add(txtRow);
line++;
}
reader.close();
}catch (IOException e){
e.printStackTrace();
}finally {
if (reader != null){
try{
reader.close();
}catch (IOException e1){
}
}
}
return list;
}
public static void writeToTxt(List<TxtRow> list){
StringBuilder sb = new StringBuilder();
for(int i=0;i<list.size();i++){
sb.append(list.get(i).getFirst()+" "+list.get(i).getSecond()).append("\r\n");
}
// write string to file
try{
FileWriter writer = new FileWriter("D:\\workspace\\test2.txt");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(sb.toString());
bw.close();
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
String filename = "D:\\workspace\\test.txt";
List<TxtRow> li = readFileByLines(filename);
System.out.println(li);
writeToTxt(li);
}
}
public class TxtRow {
private String first;
private String second;
public TxtRow() {
}
public TxtRow(String first, String second) {
this.first = first;
this.second = second;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setSecond(String second) {
this.second = second;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("\"first\":\"")
.append(first).append('\"');
sb.append(",\"second\":\"")
.append(second).append('\"');
sb.append('}');
return sb.toString();
}
}
应用场景应该是这样的吧,你的a1,b1如果只是a1,b1,那完全可以写死了都不需要第一个txt了
package com.jun.searchfieldvalues;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
*/
public class SearchFieldValues {
/**
@param args
*/
public static void main(String[] args) {
SearchFieldValues searcher = new SearchFieldValues();
searcher.mFilePath_In = "。。/input.txt";
String[] fields = {"b", "c"};
searcher.serch(fields);
}
/**
/**
/**
/**
@param fields
*/
public void serch(String[] fields) {
if (fields == null || fields.length == 0) {
System.err.println("参数中没有需要查找的字段");
return;
}
// Check input file
if (mFilePath_In == null || mFilePath_In.isEmpty()) {
System.out.println("请设置输入文件路径: mFilePath_In");
return;
}
File inFile = new File(mFilePath_In);
if (!inFile.exists()) {
System.err.println("输入文件不存在: " + mFilePath_In);
return;
}
// Check output file
if (mFilePath_Out == null || mFilePath_Out.isEmpty()) {
mFilePath_Out = mFilePath_In.substring(0, mFilePath_In.lastIndexOf(".")) + "_Result"
+ mFilePath_In.substring(mFilePath_In.lastIndexOf("."));
}
File outFile = null;
outFile = new File(mFilePath_Out);
outFile.getParentFile().mkdirs();
// 不覆盖,不追加文件,重命名输出文件
int i = 0;
while (outFile.exists()) {
mFilePath_Out = mFilePath_Out.substring(0, mFilePath_Out.lastIndexOf(".")) + "_" + (i++)
+ mFilePath_Out.substring(mFilePath_Out.lastIndexOf("."));
outFile = new File(mFilePath_Out);
}
System.out.println("Result File: " + mFilePath_Out);
FileReaderLine reader = null;
if (mCharset_In == null || mCharset_In.isEmpty()) {
try {
reader = new FileReaderLine(mFilePath_In);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
reader = new FileReaderLine(mFilePath_In, mCharset_In);
} catch (Exception e) {
e.printStackTrace();
}
}
if (reader != null) {
FileWriteLine writer = new FileWriteLine(mFilePath_Out);
if (mCharset_In != null && !mCharset_In.isEmpty()) {
writer.setCharset(mCharset_Out);
}
int[] fieldIndexes = new int[fields.length];
String line = null;
// 读取文件内容
// 第一行为字段,确定所查字段的序号
line = reader.readLine();
String[] fieldsIn = line.split(mFieldSplit_In);
StringBuilder outLine = new StringBuilder();
int fieldCount = fields.length; // 查询字段数,即输出文件第一行的字段数
if(fieldsIn == null){
System.err.println("输入文件第一行没有内容");
return;
}else if(fieldsIn.length < fieldCount){
System.err.println("输入文件第一行的字段数比需要查询的少, 无法满足查询要求. 文件字段数: " + fieldsIn.length + ", 查询字段数: " + fieldCount);
return;
}
for (i = 0; i < fieldCount; i++) {
String field = fields[i];
// 构造一行输出字段名
if (i < fieldCount - 1) {
outLine.append(field + mFieldSplit_Out);
} else {
outLine.append(field);
}
int index = -1;
for (int j = 0; j < fieldsIn.length; j++) {
if (field.equals(fieldsIn[j])) {
index = j;
break;
}
}
if (index > -1) {
fieldIndexes[i] = index;
} else {
System.err.println("所查字段不存在: " + field);
return;
}
}
// 输出字段名
writer.writeLine(outLine.toString());
long lineNum = 1; // 第一行为字段名
while ((line = reader.readLine()) != null) {
outLine = new StringBuilder();
lineNum ++;
String[] valuesIn = line.split(mValueSplit_In);
// 忽略字段值行为空和字段值数目与字段数不一致的行
if(valuesIn == null)
continue;
if(valuesIn.length != fieldsIn.length){
System.out.println("Line " + lineNum + ": 字段值数目不等于字段数, Values: " + valuesIn.length + ", Fields: " + fieldsIn.length);
continue;
}
int index = 0;
for (i = 0; i < fieldCount ; i++) {
// 构造一行输出字段值
index = fieldIndexes[i];
if (i < fieldCount - 1) {
outLine.append(valuesIn[index] + mValueSplit_Out);
} else {
outLine.append(valuesIn[index]);
}
}
// 输出查到的字段值
if (outLine.length() > 0)
writer.writeLine(outLine.toString());
}
reader.close();
if (writer != null)
writer.close();
}
}
/*
/*******************************************************************/
public class FileReaderLine {
private FileInputStream inputStream = null;
private InputStreamReader streamReader = null;
private BufferedReader reader = null;
public FileReaderLine(String path) throws Exception{
inputStream = new FileInputStream(path);
streamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(streamReader);
}
public FileReaderLine(String path, String charset) throws Exception{
inputStream = new FileInputStream(path);
streamReader = new InputStreamReader(inputStream, charset);
reader = new BufferedReader(streamReader);
}
public String readLine(){
if(reader != null){
try {
return reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void close() {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
/**********************************************/
public class FileWriteLine {
public static final String lineEnds = "\r\n";
private BufferedWriter writer;
private String mFilePath = null;
private String mCharset;
/**
*/
public FileWriteLine() {
}
public FileWriteLine(String path){
setFilePath(path);
}
public void setCharset(String charset){
mCharset = charset;
}
/**
* @param path
*/
public void setFilePath (String path){
if (path != null && !path.isEmpty()){
mFilePath = path;
File parentFile = new File(mFilePath).getParentFile();
parentFile.mkdirs();
if(writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
writer = null;
}
}
}
public String getFilePath(){
return mFilePath;
}
/**
* @param line
*/
public void writeLine(String line){
try {
if (writer == null) {
File file = new File(mFilePath);
file.getParentFile().mkdirs();
FileOutputStream output = new FileOutputStream(file, true);
OutputStreamWriter streamWriter = null;
if(mCharset == null || "".equals(mCharset)){
streamWriter = new OutputStreamWriter(output);
}else {
streamWriter = new OutputStreamWriter(output, mCharset);
}
writer = new BufferedWriter(streamWriter);
}
if(line.endsWith("\n")){
writer.append(line);
}else {
writer.append(line + lineEnds);
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable{
close();
super.finalize();
}
public void close() {
if(writer != null){
try {
writer.close();
writer = null;
} catch (IOException e) {
e.printStackTrace();
writer = null;
}
}
}
}
}
// 输入文件内容,空白字符不固定,其他分隔符修改参数即可
a b c d e f g
13 4 5 9 1 2 8
13 6 52 7 1 22 8
13 89 53 42 1 23 8
// 输出文件内容查找 [b.c]
b c
4 5
6 52
89 53
我发了一篇文章来回答,代码好看,请转向:
回答“java读取.txt的特定字段将其写入另一个.txt文本”