java導入txt
Java中將txt文件導入到mysql基本的思路,操作流獲取到文件具體信息,然後將信息拼接成mysql插入到資料庫中。
㈡ 將.txt文件中的數字 導入java中
這里不成功可能有以下幾個原因:
1、你的java沒有配置好環境變數。
方法:在命令行,測試輸入java,javac,看看是不是正常;
2.你代碼裡面要有讀寫文件的流的語句,即要加入FileInputStream語句啊,不加的話,java程序沒法讀文件的。
3你的input.txt路徑沒有配對,如果你的input.txt文件不在你的C盤用戶目錄下,需要配置路徑,比如
input.txt在D盤,需要改成D:\input.txt
㈢ 用java導入txt數據到sql server中
這個很簡單啊,
通過文件流一行一行的讀
每行的字元串通過replaceAll空格(可能是 )替換成特殊字元,注意:要用正則替換連續的空格(或 )
然後通過split這個特殊字元成數組
數組轉成表映射對象
批量插入資料庫
㈣ 用java代碼把txt文檔中資料導入到資料庫
BufferedReader input;
try {
String s = new String();
input = new BufferedReader(new FileReader("f:\\123.txt"));
while ((s = input.readLine()) != null) { // 判斷是否讀到了最後一行
String info[] = s.split(" ");
System.out.println( info[0] + " " + info[1] + " " + info[2] );
}
input.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
把info[0] + " " + info[1] + " " + info[2] 這三個值放在insert語句里就行了 經過測試
㈤ Java中如何提取TXT文件數據並講數據導入到數組里...急求
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
Scannerscanner=newScanner(newFileInputStream("d:/data.txt"));//通過FileInputStream構建Scanner
ArrayList<Integer[]>integerDataList=newArrayList<>();//初始化數據存放list,arrayList中的每一項是一條數據
while(scanner.hasNext()){
Stringline=scanner.nextLine();//讀入一行數據
String[]datas=line.split(",");//根據逗號分隔字元串
if(datas.length!=3){
//如果分割後的數據不足三個,說明數據錯誤,拋棄本條數據
continue;
}
//構建integer類型數組,保存本行數據
Integer[]integerData=newInteger[3];
//通過Integer.valueOf方法將字元串轉換為整型數字
integerData[0]=Integer.valueOf(datas[0]);
integerData[1]=Integer.valueOf(datas[1]);
integerData[2]=Integer.valueOf(datas[2]);
//將本行數據添加到所有數據的集合中
integerDataList.add(integerData);
}
//輸出所有數據
for(Integer[]integerData:integerDataList){
System.out.println(Arrays.toString(integerData));
}
}
㈥ java 怎麼導入txt的數據
txt文件里格式是什麼樣的?
import java.nio.file.*;
import java.io.*;
import java.util.stream.*;
try(var writer = new PrintWriter("/tmp/numbers.txt")){
IntStream.rangeClosed(200, 20000).forEach(writer::println); //生成一個每行一個整數的文本文件
Files.lines(Paths.get("/tmp/numbers.txt")).mapToInt(Integer::parseInt).toArray(); // 將文件中的數字讀到一個數組里
} catch(Exception e){
e.printStackTrace();
}
㈦ java中的txt導入出現中文亂碼
你現在是以UTF-8的形式去讀取文件
你換一下,用GBK吧,應該文件的編碼問題
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis,"UTF-8"))就是這行代碼
㈧ java讀取、修改、寫入txt文件
模擬:先創建一個TXT文件(內容來自控制台);然後讀取文件並在控制台輸出;最後實現對新創建的TXT文件(的數據進行排序後)的復制。分別對應三個函數,調用順序需要注意:創建、讀取、復制。
效果圖如下:綠色部分為控制台輸入的內容(當輸入end時,結束)
packagecom.;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.OutputStreamWriter;
importjava.util.Arrays;
importjava.util.Scanner;
importjava.util.Vector;
publicclassCreateAndReadTxt{
//文件名稱
publicstaticStringfileName=".txt";
publicstaticStringnewFileName=".txt";
//文件路徑
publicfinalstaticStringURL=System.getProperty("user.dir");
//CreateAndReadTxt.class.getResource("/").getPath();
//創建TXT文件
publicstaticvoidcreateTxtFile(StringfName,StringfileContent){
//創建文件
fileName=fName+fileName;
Filefile=newFile(fileName);
//可以更改
file.setWritable(true);
//判斷當前路徑下是否存在同名文件
booleanisExist=file.exists();
if(isExist){
//文件存在,刪除
file.delete();
}
//寫入文件
try{
//文件寫入對象
FileOutputStreamfos=newFileOutputStream(file);
//輸入流寫入----默認字元為GBK
OutputStreamWriterosw=newOutputStreamWriter(fos);
//寫入
osw.write(fileContent);
//寫入完畢後關閉
osw.close();
System.out.println("成功創建文件: "+fileName);
}catch(IOExceptione){
System.out.println("寫入文件失敗: "+e.getMessage());
}
}
//閱讀文件
publicstaticvoidreadFile(StringfileName){
System.out.println("開始讀取文件: "+fileName);
//產生文件對象
Filefile=newFile(fileName);
//
try{
//字元讀取
FileReaderfr=newFileReader(file);
//緩沖處理
BufferedReaderbr=newBufferedReader(fr);
Stringstr="";
while((str=br.readLine())!=null){
System.out.println(str);
}
//關閉
br.close();
fr.close();
}catch(FileNotFoundExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}catch(IOExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}
}
//文件復制
publicstaticvoidFile(StringfromFileName,StringtoFileName){
//讀取文件
Filefile=newFile(fromFileName);
try{
FileReaderfr=newFileReader(file);
BufferedReaderbr=newBufferedReader(fr);
//定義接收變數
Vector<Double>vec=newVector<Double>();
Strings="";
while(null!=(s=br.readLine())){
vec.add(Double.parseDouble(s));
}
br.close();
fr.close();
//保存到數組並進行排序
Doubledou[]=newDouble[vec.size()];
vec.toArray(dou);
Arrays.sort(dou);
System.out.println("========復制文件=========");
//寫入新文件
newFileName="副本"+newFileName;
FilenewFile=newFile(toFileName);
FileOutputStreamfos=newFileOutputStream(newFile,true);
OutputStreamWriterosm=newOutputStreamWriter(fos);
for(Doubled:dou){
osm.write(d.doubleValue()+"
");
}
osm.close();
fos.close();
}catch(FileNotFoundExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}catch(IOExceptione){
System.out.println("讀取文件失敗: "+e.getMessage());
}
}
publicstaticvoidmain(String[]args){
/**
*構造數據
*/
Scannerscan=newScanner(System.in);
StringBuildersb=newStringBuilder();
Strings="";
while(!("end".equals(s=scan.next()))){//當輸入end時,結束
sb.append(s);
sb.append("
");
}
scan.close();
/**
*使用數據
*/
CreateAndReadTxt.createTxtFile("creat",sb.toString());
CreateAndReadTxt.readFile(fileName);
System.out.println(fileName);
CreateAndReadTxt.File(fileName,newFileName);
CreateAndReadTxt.readFile(newFileName);
}
}
㈨ 用java如何將txt文件導入mysql
Java中將txt文件導入到mysql基本的思路就是先使用I/O操作流獲取到文件具體信息,然後將信息拼接成mysql插入到資料庫中,示例如下:
1、先讀取txt文件的內容,文件內容可以按照一定的規律進行排列,這樣程序讀取就方便。
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.config.Constants;
import com.utils.UUIDUtil;
/**
* txt文本數據 採集類
*
* @see
*/
public class UserDataGather {
public static final String TXT_FILE_PATH = "D://testUser.txt";
public static final String openFileStyle = "r";
public static final String fieldLimitChar = ".";
public static final int fieldAllCount = 1;
public static final String default_password = "PTMD0309";
public Integer count = 0;
private String FltNum;
public String UUID;
/**
* 功能:解析文本文件
*/
public void loadFile() {
try {
RandomAccessFile raf = new RandomAccessFile(TXT_FILE_PATH, openFileStyle);
String line_record = raf.readLine();
while (line_record != null) {
// 解析每一條記錄
parseRecord(line_record);
line_record = raf.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 功能:具體解析每一條記錄,這里可以增加很多對記錄的解析判斷條件,如是否為字母、
*/
@SuppressWarnings("static-access")
private void parseRecord(String line_record) throws Exception {
//拆分記錄
// String[] fields = line_record.split(fieldLimitChar);
// System.out.println(tranStr(line_record)+"Ok");
String temp = line_record.substring(line_record.indexOf(fieldLimitChar, 0), line_record.indexOf(" ", line_record.indexOf(fieldLimitChar, 0)));
// if (fields.length == fieldAllCount) {
//
FltNum = tranStr(temp).trim().replace(fieldLimitChar,"").replace(" ","");
// System.out.println(FltNum);
if(FltNum.length()>=4){
if(!isNumeric(FltNum)){
// System.out.println(generateSql(FltNum)[0].toString());
// System.out.println(generateSql(FltNum)[1].toString());
count++;
String[] temp1 = generateSql(FltNum);
MyFile mf = new MyFile();
mf.creatTxtFile("insertPinTuUserSql");
mf.writeTxtFile(temp1[0].toString());
mf.creatTxtFile("UUID");
mf.writeTxtFile(temp1[1].toString()+",");
}
}else if(FltNum.length() ==2 || FltNum.length() ==3){
if(!isNumeric(FltNum)){
if(!isTwoCharacter(FltNum)){
// System.out.println(generateSql(FltNum)[0].toString());
// System.out.println(generateSql(FltNum)[1].toString());
count++;
String[] temp2 = generateSql(FltNum);
MyFile mf = new MyFile();
mf.creatTxtFile("insertPinTuUserSql");
mf.writeTxtFile(temp2[0].toString());
mf.creatTxtFile("UUID");
mf.writeTxtFile(temp2[1].toString()+",");
}
}
}
// InsertDB db = new InsertDB();
//
// db.insertDB(FltNum);
// }
}
@SuppressWarnings("static-access")
public String[] generateSql(String userName) throws IOException{
StringBuffer sbf = new StringBuffer();
String[] str = new String[2];
String uuid = UUIDUtil.getUUID();
sbf.append("insert into user values('"+uuid+"','" + userName +"','"+default_password+"',"+Constants.ENABLED+","+Constants.NUllDELETE+","+Constants.AUDITING+",'"+uuid+"@164.com','"+formatDateTime()+"',"+Constants.REGEDIT_USER+");/n");
sbf.append("insert into users values('"+uuid+"',"+ null+","+Constants.MALE+","+null+","+null+",'60.176.36.250','"+formatDateTime()+"',"+null+","+null+","+null+","+null+","+null+","+null+",0,"+null+","+null+",0,0,0,'"+formatDateTime()+"','1036',0,"+null+","+null+","+null+","+null+","+null+",'11',"+null+","+null+","+null+","+null+","+null+");/n");
sbf.append("insert into user_user_group values('"+uuid+"','"+ uuid +"','"+Constants.PERSONAL_USER+"');/n");
UUID = uuid;
str[0]=sbf.toString();
str[1]=UUID;
return str;
}
public String formatDateTime(){
Date date = new Date();
/**
* 時間格式化2009-12-31 09:04:31
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
return sdf.format(date);
}
private String tranStr(String oldstr) {
String newstr = "";
try {
newstr = new String(oldstr.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return newstr;
}
public static boolean isNumeric(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static boolean isTwoCharacter(String str){
String regEx="[a-zA-Z0-9]{2,3}";
Pattern p=Pattern.compile(regEx);
Matcher m=p.matcher(str);
return m.find();
}
}
2、連接資料庫執行數據導入
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
* 插入資料庫 生成sql語句
*
* created on Mar 8, 2010
* @see
*/
public class InsertDB {
private static final String user = "pintu";
private static final String pwd = "pintu";
private static final String url = "jdbc:mysql://192.168.10.6:3306/pintu";
private static final String driver = "com.mysql.jdbc.Driver";
public static Connection getCon() {
Connection con = null;
try {
Class.forName(driver).newInstance();
con = (Connection) DriverManager.getConnection(url, user, pwd);
if (con != null) {
System.out.println("你已連接到資料庫:" + con.getCatalog());
}
} catch (Exception e) {
System.out.println("連接資料庫失敗!");
e.printStackTrace();
}
return con;
}
public boolean insertDB(String FltNum) {
Connection con = null;
Statement stm = null;
boolean flag = false;
String sql = "insert into t_FltPsgInfo values('" + FltNum +
// "','"
// + FltLine + "','" + FltDate + "','" + PsgName + "','" + PsgType
//
// + "','" + PsgSex + "','" + PsgCab + "','" + PsgSeatNo + "','"
//
// + PsgInfo +
"')";
try {
con = getCon();
stm = (Statement) con.createStatement();
int i = stm.executeUpdate(sql);
if (i > 0) {
flag = true;
System.out.println(flag + "插入數據成功!");
}
} catch (Exception e) {
flag = false;
e.printStackTrace();
} finally {
close(null, stm, con);
}
return flag;
}
//關閉相關連接
public void close(ResultSet rs, Statement stm, Connection con) {
if (rs != null)
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
if (stm != null)
try {
stm.close();
} catch (Exception e) {
e.printStackTrace();
}
if (con != null)
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
㈩ java向txt中插入數據
在不讀取文件內容的前提下插入行,用PrintWriter是做不到的。
PrintWriter只能從頭寫,或者從尾部追加。
你這個想法可以用RandomAccessFile或許可以實現,不過很麻煩。
最簡單的就是讀出每行文本,放到集合里,然後在指定的索引處插入行。