gu123xin
2018-08-08 07:12
采纳率: 95.2%
浏览 822

java将.txt数据与mysql比较,排序成为mysql里的顺序,并导入到指定的.txt标签

假设数据库的内容是这样图片说明
.txt文本的内容是这样图片说明
需要将.txt内容读取,并排列成为mysql数据库一样的顺序(数据库里面是没有name这个标签的),然后再插入另一个.txt文本里面,像这样,左边是没有插入前,右边是插入后的结果图片说明,这个要怎么样实现呢?利用数组可以吗?麻烦发个代码看一下, 详细些,谢谢大牛们。

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

14条回答 默认 最新

  • 已采纳

    ![图片说明](https://img-ask.csdn.net/upload/201808/09/1533821981_337319.png)图片说明
    这个是文件 配合代码看下 我没有连接数据库 查询出来的直接放那个list中就可以了我有注释哪里你看下

    已采纳该答案
    打赏 评论
  • gu123xin 2018-08-08 07:19

    mysql数据库比较大的,该怎么样选取“id”存入数组

    打赏 评论
  • CN长城 2018-08-08 07:28

    在Java端这个事好办,可以以数组形式操作,前期对于mysql数据库进行流式读取,放入数组中。后期读取.txt,并放入新的数组中,遍历就行了

    打赏 评论
  • 一只眼足矣看码 2018-08-08 08:04

    按照 行,每行读出来,然后在txt再打印出来,for循环,格式按照自己方式打印出来就可以

    打赏 评论
  • gu123xin 2018-08-08 08:06

    会的大牛可以写个代码,感激不仅,我java才刚刚学习,不会操作

    打赏 评论
  • 非要用java吗 java写起来有点麻烦 python可以吗

    打赏 评论
  • weixin_40852944 2018-08-08 09:39

    大概写了一下实现思路,你按照这个思路写一下应该就可以,有些注释的地方,需要你来自己手工敲下代码实现

     public class TestCase {
        public static void main(String[] args) {
            List<User> dbUsers = null;//...从数据库中查询出 数据集合
            List<User> txtUsers = null;//...从txt读取出用户集合
            List<User> sortUsers = new ArrayList<User>(txtUsers.size());//...申明排序后的用户集合
            for(User dbUser: dbUsers){
                for(User txtUser : txtUsers){
                    //如果txtUser = dbUser 则加入排序后的用户集合
                    if(dbUser.getId().equals(txtUser.getId())){
                        sortUsers.add(txtUser);
                        break;
                    }
                }
            }
    
            List<OtherObject> finalTextObjects = null; //从最后的txt文件中按行及分割 , 解析出java对象集合;
            for(int i=0;i<finalTextObjects.size();i++){
                OtherObject otherObject = finalTextObjects.get(i);
                otherObject.setName(sortUsers.get(i).getName());
            }
            //然后将 finalTextObjects从新写入到 txt文件中;
        }
    
    }
    
    //第一个txt对应的java对象
    class User{
    
        private String id;
    
        private String name;
    
        // ...getter setter
    }
    //最后一个txt对应的java对象
    class OtherObject{
        private String host;
        private String name;
        private String home;
        private String news;
        // ...getter setter
    }
    
    打赏 评论
  • gu123xin 2018-08-08 10:36

    分不多,希望有空的大神可以帮忙,谢谢大家了

    打赏 评论
  • _zming 2018-08-09 01:34

    如果数据量不大的话可以用TreeMap进行记录排序再写入文件
    1:读取txt文件记录,a
    2.判断此记录a在数据库中的位置,假如是3,并将序号压入map,threeMap.put(new Integer(3), a);
    3.循环操作1-2直到txt读取完毕

    4.遍历map的值写入到txt文件

    细节问题可以查看百度,比如如何使用treemap

    打赏 评论
  • wjintao 2018-08-09 07:52
    private void LoadTxt(String FilePath, HashMap<String, String> TxtData) {
        String line = "";
        try {
            FileReader mFileReader = new FileReader(FilePath);
    
            BufferedReader in = new BufferedReader(mFileReader);
            try {
                line = in.readLine();
                while (line != null) {
                    SplitData(line, TxtData);
                    line = in.readLine();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.e("TAG", String.format("IOException:%s", e.getMessage()));
            }
        } catch (FileNotFoundException e) {
            Log.e("TAG", String.format("FileNotFoundException:%s", e.getMessage()));
        }
    
        Set<Entry<String, String>> DataEntries = TxtData.entrySet();
        if (DataEntries != null) {
            Iterator<Entry<String, String>> iterator = DataEntries.iterator();
            while (iterator.hasNext()) {
                HashMap.Entry<String, String> entry = iterator.next();
                Log.e("TAG", String.format("Key:%s,Value:%s", entry.getKey(), entry.getValue()));
            }
        }
        // use LinkedList to sort, because insertion of elements in linked list
        // is faster than ArrayList.
        LinkedList<HashMap.Entry<String, String>> aList = new LinkedList<HashMap.Entry<String, String>>(DataEntries);
        // sorting the List
        Collections.sort(aList, new Comparator<HashMap.Entry<String, String>>() {
            @Override
            public int compare(HashMap.Entry<String, String> ele1, HashMap.Entry<String, String> ele2) {
                return ele1.getKey().compareTo(ele2.getKey());
            }
        });
    
        // Storing the list into Linked HashMap to preserve the order of
        // insertion.
        HashMap<String, String> aMap2 = new LinkedHashMap<String, String>();
        for (HashMap.Entry<String, String> entry : aList) {
            aMap2.put(entry.getKey(), entry.getValue());
        }
        // printing values after sorting of map
        Log.e("TAG", "Values and Keys after sorting ");
        for (HashMap.Entry<String, String> entry : aMap2.entrySet()) {
            Log.e("TAG", String.format("Key:%s,Value:%s", entry.getKey(), entry.getValue()));
        }
    }
    
    public void SplitData(String line, HashMap<String, String> TxtData) {
        String[] Key_Value = line.split(",");
        TxtData.put(Key_Value[0], Key_Value[1]);
    }
    希望可以帮到一点点忙
    
    打赏 评论
  • 张音乐 2018-08-09 10:34

    老板,写了一下午

    import org.yaml.snakeyaml.reader.UnicodeReader;
    
    import java.io.*;
    import java.util.*;
    
    public class ReadTxt {
    
        public static Map<String,String> readFromTxt(String fileName) {
            List<TxtRow> list = new ArrayList<>();
            BufferedReader reader = null;
            Map<String,String> map = new HashMap<String,String>();
            try{
                FileInputStream fileInputStream = new FileInputStream(new File(fileName));
                UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
    
                reader = new BufferedReader(unicodeReader);
                String tempString = null;
                int line = 1;
                while ((tempString = reader.readLine()) != null) {
                    System.out.println("line " + line + ": " + tempString);
                    tempString.trim();    //清空首尾的空格
                    System.out.println("-------------间隔不固定--------------------");
                    //String string = tempString.replaceAll(" {1,}", " ");    //替换多个空格
                    String [] strs2 = tempString.split(",");     //以空格作为分割,打印输出,注意txt中不要出现tab打出来的缩进空格
                    map.put(strs2[0],strs2[1]);
                    line++;
                }
                reader.close();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if (reader != null){
                    try{
                        reader.close();
                    }catch (IOException e1){
    
                    }
                }
            }
            return map;
        }
    
        public static List<Map<String,String>> readFromTxt2(String fileName) {
            List<TxtRow> list = new ArrayList<>();
            BufferedReader reader = null;
            List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
    
            try{
                FileInputStream fileInputStream = new FileInputStream(new File(fileName));
                UnicodeReader unicodeReader = new UnicodeReader(fileInputStream);
    
                reader = new BufferedReader(unicodeReader);
                String tempString = null;
                int line = 1;
                while ((tempString = reader.readLine()) != null) {
                    Map<String,String> map = new LinkedHashMap<String,String>();
                    System.out.println("line " + line + ": " + tempString);
                    tempString.trim();    //清空首尾的空格
                    if(line==1){
                        String [] strs2 = tempString.split("\\|");     //以空格作为分割,打印输出,注意txt中不要出现tab打出来的缩进空格
                        map.put("host",strs2[0].trim());
                        map.put("name",strs2[1].trim());
                        map.put("home",strs2[2].trim());
                        map.put("new",strs2[3].trim());
                    }else{
                        String string = tempString.replaceAll(" {1,}", "");   //替换多个空格
                        String [] strs2 = string.split(",");     //以空格作为分割,打印输出,注意txt中不要出现tab打出来的缩进空格
                        map.put("host",strs2[0].trim());
                        map.put("name","");
                        map.put("home",strs2[2].trim());
                        map.put("new",strs2[3].trim());
                    }
                    mapList.add(map);
                    line++;
                }
    
                reader.close();
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                if (reader != null){
                    try{
                        reader.close();
                    }catch (IOException e1){
    
                    }
                }
            }
            return mapList;
        }
    
        public static void writeToTxt(List<Map<String,String>> list){
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<list.size();i++){
                if(i==0){
                    sb.append(list.get(i).get("host")+"a\u007C"+list.get(i).get("name")+"a\u007C"+list.get(i).get("home")+"a\u007C"+list.get(i).get("new")).append("\r\n");
                }else{
                    sb.append(list.get(i).get("host")+","+list.get(i).get("name")+","+list.get(i).get("home")+","+list.get(i).get("new")).append("\r\n");
                }
            }
            try{
                FileWriter writer = new FileWriter("D:\\workspace\\test3.txt");
                BufferedWriter bw = new BufferedWriter(writer);
                bw.write(sb.toString());
                bw.close();
                writer.close();
            }catch(Exception e){
                e.printStackTrace();
            }
    
        }
    }
    
    
    
     import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBHelper {
    
        private static final String driver = "com.mysql.jdbc.Driver";//数据库驱动
        private static final String url = "jdbc:mysql://localhost:3306/gumysql?useUnicon=true&characterEncoding=UTF-8";
        private static final String username = "root";
        private static final String password = "root";
    
        static
        {
            try 
            {
                Class.forName(driver);
            }
            catch (Exception e)
            {
    
                e.printStackTrace();
            }
        }
    
        private static Connection conn = null;
        //单例模式返回数据库连接
        public static Connection getConnection() throws Exception
        {
            if(conn == null)
            {
                conn = DriverManager.getConnection(url, username, password);
                return conn;
            }
            else
            {
                return conn;
            }
        }
    }
    
    
     import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class ReadDB {
    
        public List<String> query() {
            Connection conn = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            String sql = " select * from compare; ";
            List<String> mapList = new ArrayList<String>();
            try
            {
                conn = DBHelper.getConnection();
                stmt = conn.prepareStatement(sql);
                rs = stmt.executeQuery();
                while(rs.next())
                {
                    mapList.add(rs.getString("id"));
                }
                return mapList;
            }
            catch(Exception e)
            {
                e.printStackTrace();
                return null;
            }
            finally
            {
                if(rs!=null)
                {
                    try
                    {
                        rs.close();
                        rs = null;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                if(stmt!=null)
                {
                    try
                    {
                        stmt.close();
                        stmt = null;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    
     import java.util.*;
    
    public class App {
    
        public static void main(String args[]){
    
            //读取数据库
            ReadDB readDB = new ReadDB();
            List<String> mapList =  readDB.query();
            System.out.println(mapList);
            //[abc1, abc2, abc3, abc4, abc5, abc6, abc7, abc8]
    
            //读取txt
            String filename = "D:\\workspace\\test.txt";
            Map<String,String> map = ReadTxt.readFromTxt(filename);
            System.out.println("map:"+map);
    
            //排序
            Map<String,String> newMap = new LinkedHashMap<String,String>();
            for(int i=0;i<mapList.size();i++){
                String key = mapList.get(i).toString();
                for(Map.Entry obj : map.entrySet()) {
                    String oKey = (String) obj.getKey();
                    System.out.println(oKey+","+key);
                    String value = (String) obj.getValue();
                    if(oKey.equals(key)){
                        newMap.put(key,value);
                        break;
                    }
                }
                System.out.println();
            }
    
            System.out.println("newMap:"+newMap);
            //List listKey = new ArrayList();
            List<String> listValue = new ArrayList<String>();
            Iterator it = newMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                listValue.add(newMap.get(key));
            }
            System.out.println("listValue:"+listValue);
    
            //读取修改前的txt
            String filename1 = "D:\\workspace\\test2.txt";
            List<Map<String,String>> resultTxtFrom = ReadTxt.readFromTxt2(filename1);
            System.out.println("resultTxtFrom:"+resultTxtFrom);
    
            for(int i=1;i<resultTxtFrom.size();i++){
                resultTxtFrom.get(i).replace("name",listValue.get(i-1).toString());
            }
    
            System.out.println("newResultTxtFrom:"+resultTxtFrom);
    
            //写进入txt
            ReadTxt.writeToTxt(resultTxtFrom);
    
        }
    }
    
    

    test文件
    图片说明

    test2文件
    图片说明

    test3在程序执行之前为空,写入后

    图片说明

    数据库为:
    图片说明

    需要导入的jar包题主可以找我,我私发给你。

    打赏 评论
  • 张音乐 2018-08-09 10:46

    图片说明

    需要导入这两个jar包,一个是数据库驱动,另外一个是防止读取txt文件出现equals不相等问题的。

    打赏 评论
  • import java.io.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    public class ReadTxt {

    public static void Read() throws Exception{
    
        File file = new File("d://2.txt");
    
        FileWriter fileWriter = new FileWriter(file);
    
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    
        List<DataColumn> dataTxt = new ArrayList<DataColumn>();
    
        List<DataColumn> dataColumn = new ArrayList<DataColumn>();
    
        //构建数据
        DataColumn data = new DataColumn();
        data.setId("weq");
        data.setNamme("2132");
        dataColumn.add(data);
    
        DataColumn data1 = new DataColumn();
        data1.setId("adad");
        data1.setNamme("2132");
        dataColumn.add(data1);
    
        DataColumn data2 = new DataColumn();
        data2.setId("abc2");
        data2.setNamme("2132");
        dataColumn.add(data2);
    
        String filePath = "d:\\1.txt";
        File fileName = new File(filePath);
        InputStreamReader reader = new InputStreamReader(new FileInputStream(fileName));
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line = "";
        List<DataColumn> list = new ArrayList<DataColumn>();
    
        while ((line = (bufferedReader.readLine())) != null) {
            if (null != line.split(",")[0] && null != line.split(",")[1]) {
                DataColumn tempColumn = new DataColumn();
                tempColumn.setId(line.split(",")[0]);
                tempColumn.setNamme(line.split(",")[1]);
                list.add(tempColumn);
            }
        }
    
        Iterator<DataColumn> iterator = dataColumn.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next().getId();
            DataColumn tempColunm = null;
            for (DataColumn column :list) {
                if (next.equals(column.getId())) {
                    tempColunm = new DataColumn();
                    tempColunm.setId(column.getId());
                    tempColunm.setNamme(column.getNamme());
                    dataTxt.add(tempColunm);
                    iterator.remove();
                }
            }
        }
    
        for (int i = 0;dataTxt.size() > i;i++) {
            bufferedWriter.write(dataTxt.get(i).getId()+"\t"+dataTxt.get(i).getNamme()+"\t\t\t\t\t\t\t"+list.get(i).getId()+"\t"+list.get(i).getNamme()+"\n");
        }
    
        bufferedWriter.flush();
        bufferedWriter.close();
    }
    
    public static void main(String args[]) {
        try {
            Read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

    
    

    public class TextColumn {

    private String id;
    
    private String namme;
    
    private String host;
    
    private String newString;
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getNamme() {
        return namme;
    }
    
    public void setNamme(String namme) {
        this.namme = namme;
    }
    
    public String getHost() {
        return host;
    }
    
    public void setHost(String host) {
        this.host = host;
    }
    
    public String getNewString() {
        return newString;
    }
    
    public void setNewString(String newString) {
        this.newString = newString;
    }
    

    }

    public class DataColumn {

    private String id;
    
    private String namme;
    
    private String host;
    
    private String newString;
    
    private TextColumn textColumn;
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getNamme() {
        return namme;
    }
    
    public void setNamme(String namme) {
        this.namme = namme;
    }
    
    public String getHost() {
        return host;
    }
    
    public void setHost(String host) {
        this.host = host;
    }
    
    public String getNewString() {
        return newString;
    }
    
    public void setNewString(String newString) {
        this.newString = newString;
    }
    
    public TextColumn getTextColumn() {
        return textColumn;
    }
    
    public void setTextColumn(TextColumn textColumn) {
        this.textColumn = textColumn;
    }
    

    }

    打赏 评论
  • grace.free 2018-08-10 02:23
        try{
            ResultSet res = null;//这里 自己查询结果 
            //存储数据库顺序的map
            Map<String, String> map = new HashMap<>();
            map.put(res.getString("id"), null);
    
    
            //读取文件  
            map.put("你的txt中的跟id字段对应的位置的数据", "你的txt中的跟id字段对应的位置的数据对应的值");
    
            //现在这个map就是跟数据库排序一样的了直接遍历map放到另一个txt中就行了
        }catch(Exception e){
            System.out.println("操作错误");
        }
    
    打赏 评论

相关推荐 更多相似问题