笔记:Java 创建txt文件并向其写入数据,再将数据存入到Mysql数据表

需要用到的jar包:图片描述

如果maven直接add找不到,可以到maven 库中找jar包对应的xml语句:
https://mvnrepository.com/

创建TXT文件并写入数据:
PS:最后注释掉的为测试方法;

//WriteFile.java
//用于将信息写入文本文件

package dbUtil;

import java.io.*;

//WriteFile.java
//用于将信息写入文本文件

public class WriteFile {
    private int count = 0;
public int getCount() {
    return count;
}

public void setCount(int count) {
    this.count = count;
}

public void write() throws Exception {

    File f = new File("data\\stu.txt");//stu.txt创建在和src同级目录下的“data”文件夹中(和src目录并列)
    f.createNewFile();
    FileOutputStream fos = new FileOutputStream(f);
    DataOutputStream dos = new DataOutputStream(fos);

    this.count++;
    dos.writeUTF("Rose");
    dos.writeInt(80);
    dos.writeInt(75);
    dos.writeInt(65);
    dos.writeInt(50);

    this.count++;
    dos.writeUTF("Lily");
    dos.writeInt(90);
    dos.writeInt(100);
    dos.writeInt(100);
    dos.writeInt(100);

    this.count++;
    dos.writeUTF("Tom");
    dos.writeInt(60);
    dos.writeInt(70);
    dos.writeInt(55);
    dos.writeInt(75);

    this.count++;
    dos.writeUTF("Tracy");
    dos.writeInt(60);
    dos.writeInt(80);
    dos.writeInt(75);
    dos.writeInt(80);

    this.count++;
    dos.writeUTF("Moon");
    dos.writeInt(80);
    dos.writeInt(70);
    dos.writeInt(90);
    dos.writeInt(85);

    this.count++;
    dos.writeUTF("Tranlie");
    dos.writeInt(100);
    dos.writeInt(80);
    dos.writeInt(90);
    dos.writeInt(85);

    dos.flush();
    dos.close();

}

/**
 * 读TXT文件内容
 * @param string
 * @return
 */
/*public String readTxtFile(String string) throws Exception {
    String result = null;
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
        fileReader = new FileReader(string);
        bufferedReader = new BufferedReader(fileReader);
        try {
            String read = null;
            while ((read = bufferedReader.readLine()) != null) {
                result = result + read + "\r\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        if (fileReader != null) {
            fileReader.close();
        }
    }
    System.out.println("读取出来的文件内容是:" + "\r\n" + result);
    return result;
}

public static void main(String[] args) {
    WriteFile writeFile = new WriteFile();
    try {
        writeFile.readTxtFile("data\\stu.txt");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}*/
 /**
     * 读TXT文件内容
     * @param string
     * @return
     */
    /*public String readTxtFile(String string) throws Exception {
        String result = null;
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(string);
            bufferedReader = new BufferedReader(fileReader);
            try {
                String read = null;
                while ((read = bufferedReader.readLine()) != null) {
                    result = result + read + "\r\n";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (fileReader != null) {
                fileReader.close();
            }
        }
        System.out.println("读取出来的文件内容是:" + "\r\n" + result);
        return result;
    }

    public static void main(String[] args) {
        WriteFile writeFile = new WriteFile();
        try {
            writeFile.readTxtFile("data\\stu.txt");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/
}

读取TXT文件中的信息:
//ReadFile.java
//用于返回文本中的信息

package dbUtil;
import java.io.*;  

//ReadFile.java
//用于返回文本中的信息

public class ReadFile {
    public String[] read()throws Exception{  
        WriteFile wr = new WriteFile();  
        wr.write();  
        String str[] = new String[wr.getCount()];  

        File f = new File("data\\stu.txt");  
        FileInputStream fis = new FileInputStream(f);  
        DataInputStream dis = new DataInputStream(fis);  

        for (int i=0 ; i<str.length ; i++){  
            str[i] = "'"+dis.readUTF()+"'"+","+dis.readInt()+","+dis.readInt()+","+dis.readInt()+","+dis.readInt();  
            System.out.println(str[i]) ;  
        }  

        return str ;  
    } 
}

//InsertDB.java
//创建数据表
//把ReadFile返回的信息更新到MySql数据库

package dbUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

//InsertDB.java
//把ReadFile返回的信息更新到MySql数据库

public class InsertDB {
    public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
    public static final String DBURL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    public static final String DBUSER = "Uname";
    public static final String DBPASSWORD = "password";

    public static void main(String[] args) throws Exception {
        Connection conn = null;
        Class.forName(DBDRIVER);
        conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
        Statement stmt = conn.createStatement();

        //判断数据库中是否存在同名数据表,如果没有,就新建数据表
        ResultSet rs = conn.getMetaData().getTables(null, null, "scores", null);
        if (rs.next()) {
            // yourTable exist
            System.out.println("Your table exist.");
        } else {
            // yourTable not exist
            String sqlCreateTable = "create table scores(name varchar(50),chinese int,english int,math int,scintist int);";
            PreparedStatement stmt1 = conn.prepareStatement(sqlCreateTable);
            stmt1.execute();
            System.out.println("yourTable has been crated.");
        }

        //读取刚刚写入到txt文件中的数据,并写入到数据表中
        String temp[] = new ReadFile().read();
        for (int i = 0; i < temp.length; i++) {
            String sql = "INSERT INTO scores(name,chinese,english,math,scintist) VALUE(" + temp[i] + ")";
            stmt.executeUpdate(sql);
        }

        stmt.close();
        conn.close();
    }
}

MySQL数据库中结果如下:
图片描述

参考:
1、Java-把文本中的数据插入到MySql数据库:http://www.cnblogs.com/Jesuca/archive/2010/01/05/1952264.html
2、判断数据表是否存在:http://blog.csdn.net/yuansicau/article/details/1772682

扫描二维码关注公众号,回复: 3279043 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_39108466/article/details/79542311
今日推荐