ggx1abc
gu123xin
2018-08-06 09:04
采纳率: 95.2%
浏览 2.0k
已采纳

java需要从.txt文本里读取特定的字段,并写入另一个.txt

读取之前图片说明
读取之后图片说明
a,b,c,....e是表示标签,先的是数据,我需要读取特定标签下面的数据,麻烦写个代码,谢谢,我刚学java,超级菜鸟,别嘲笑,现在力求进步,谢谢大佬们,运行成功,就给币。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

9条回答 默认 最新

  • batterMRTAN
    batterMRTAN 2018-08-06 10:09
    已采纳
    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"));
            String[] strs = {"a", "b", "d", "e"};//要读的标签
            int num[] = new int[strs.length];//每个标签的位置
            String[] left = new String[strs.length];
            String[] right = new String[strs.length];
            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(" ");
                for (int i = 0; i < strs.length; i++) {
                    for (int j = 0; j < infoArraay.length; j++) {
                        int begin = 0;
                        if((begin=infoArraay[j].indexOf(strs[i]))!=-1) {
                            num[i] = j;
                            String leftStr = infoArraay[j].substring(0, begin);;
                            String rightStr = infoArraay[j].substring(begin+strs[i].length()-1, infoArraay[j].length()-1);
                            left[i] = leftStr;
                            right[i] = rightStr;
                            writer.write(infoArraay[j]+" ");
                            break;
                        }
                    }
                }
                writer.newLine();
            }
            while((line = reader.readLine()) != null) {//逐行的读
                String[] infoArraay = line.split(" ");
                String str = "";
                for (int i = 0; i < num.length; i++) {
                    str += infoArraay[num[i]].replace(left[i], "").replace(right[i], "")+",";
                }
                str = str.substring(0, str.length()-1);
                writer.write(str);
                writer.newLine();
            }
            reader.close();
            writer.close();
        }
    }
    

    改了下,你试试
    运行前
    a b c d .....e.....
    a1 b1 c1 d1 .....e1.....
    a2 b2 c2 d2 .....e2.....
    a3 b3 c3 d3 .....e3.....
    a4 b4 c4 d4 .....e4.....
    a5 b5 c5 d5 .....e5.....
    a6 b6 c6 d6 .....e6.....
    a7 b7 c7 d7 .....e7.....
    a8 b8 c8 d8 .....e8.....
    a9 b9 c9 d9 .....e9.....
    运行后
    a b d e
    a1,b1,d1,e1
    a2,b2,d2,e2
    a3,b3,d3,e3
    a4,b4,d4,e4
    a5,b5,d5,e5
    a6,b6,d6,e6
    a7,b7,d7,e7
    a8,b8,d8,e8
    a9,b9,d9,e9

    点赞 评论
  • ggx1abc
    gu123xin 2018-08-06 09:05

    不是e8,是e7,也就是数据了。其实都无所谓

    点赞 评论
  • phenix2009
    白色一大坨 2018-08-06 09:16

    不会java,好气啊,不过从思路上来说,你就是逐行读取,然后按字符串拆分,之后找出需要的列,写入到新的文件内就可以。

    点赞 评论
  • qq_29777207
    张音乐 2018-08-06 09:18

    图片说明

     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();
        }
    }
    
    

    图片说明

    点赞 评论
  • batterMRTAN
    batterMRTAN 2018-08-06 09:23
     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"));
            String[] strs = {"a", "b", "d", "e"};//要读的标签
            int num[] = new int[strs.length];//每个标签的位置
            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");
                for (int i = 0; i < strs.length; i++) {
                    for (int j = 0; j < infoArraay.length; j++) {
                        if(infoArraay[j].equals(strs[i])) {
                            num[i] = j;
                            writer.write(infoArraay[j]+"\t");
                            break;
                        }
                    }
                }
                writer.newLine();
            }
            while((line = reader.readLine()) != null) {//逐行的读
                String[] infoArraay = line.split("\t");
                String str = "";
                for (int i = 0; i < num.length; i++) {
                    str += infoArraay[num[i]]+",";
                }
                str = str.substring(0, str.length()-1);
                writer.write(str);
                writer.newLine();
            }
            reader.close();
            writer.close();
        }
    }
    

    我这全部都是制表符,txt没有空格的图片说明图片说明
    如果你的txt文件的空白地方是空格要把\t换成空格

    点赞 评论
  • batterMRTAN
    batterMRTAN 2018-08-06 09:24
     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"));
            String[] strs = {"a", "b", "d", "e"};//要读的标签
            int num[] = new int[strs.length];//每个标签的位置
            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(" ");
                for (int i = 0; i < strs.length; i++) {
                    for (int j = 0; j < infoArraay.length; j++) {
                        if(infoArraay[j].equals(strs[i])) {
                            num[i] = j;
                            writer.write(infoArraay[j]+" ");
                            break;
                        }
                    }
                }
                writer.newLine();
            }
            while((line = reader.readLine()) != null) {//逐行的读
                String[] infoArraay = line.split(" ");
                String str = "";
                for (int i = 0; i < num.length; i++) {
                    str += infoArraay[num[i]]+",";
                }
                str = str.substring(0, str.length()-1);
                writer.write(str);
                writer.newLine();
            }
            reader.close();
            writer.close();
        }
    }
    

    空格的

    点赞 评论
  • ggx1abc
    gu123xin 2018-08-06 09:54

    图片说明

    点赞 评论
  • batterMRTAN
    batterMRTAN 2018-08-06 10:21

    你的文件是不是有多个空格啊?

    点赞 评论
  • ApatheCrazyFan
    ApacheCrazyFan 2018-08-07 01:51

    试试这个:

     public class Test {
        public static void main(String[] args){
            File fileR = new File("C:/Users/CXDOG/Desktop/testR.txt");
            File fileW = new File("C:/Users/CXDOG/Desktop/testW.txt");
            try {
                BufferedReader br = new BufferedReader(new FileReader(fileR));
                BufferedWriter bw = new BufferedWriter(new FileWriter(fileW ));
                String s;
                String[] ss;
    
                Pattern p = Pattern.compile("(\\s)+");
                while( (s = br.readLine() ) != null){
                    System.out.println(s);
                    Matcher m = p.matcher(s);
                    if (m.find() ){
                        s = s.replaceAll(m.group(1), ",");
                        bw.write(s);
                        bw.newLine();
                        bw.flush();
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    你自己看着封装优化

    点赞 评论

相关推荐