一.java中如何将Excel中的数据导入到Mysql
你可以用JXL做。读到数据库,可以通过jxl来实现,可以把EXCEL文档上传到系统的上传目录下后,然后再取得这个文件,或者直接取得这个文件,对这个文件进行操作。
例子:
public void addCustomerAssign(File file,SysExpo expo,SysUser user1)//添加客服中心数据
{
jxl.Workbook rwb = null;
try{
//构建Workbook对象, 只读Workbook对象
//直接从本地文件创建Workbook
//从输入流创建Workbook
InputStream is = new FileInputStream(file);
rwb = Workbook.getWorkbook(is);
String createTime = DateUtil.getDateTime( "yyyy-MM-dd HH:mm ",new Date()).toString();
//Sheet(术语:工作表)就是Excel表格左下角的Sheet1,Sheet2,Sheet3但在程序中
//Sheet的下标是从0开始
//获取第一张Sheet表
Sheet rs = rwb.getSheet(0);
//获取Sheet表中所包含的总列数
// int rsColumns = rs.getColumns();
//获取Sheet表中所包含的总行数
int rsRows = rs.getRows();
//获取指定单元格的对象引用
// rs.getCell(列,行);
for(int i=1;i <rsRows;i++){//如第一行为属性项则从第二行开始取数据(int i=0 ;i <rsRows;i++)
//for(int j=0;j <rsColumns;j++){
//Cell cell = rs.getCell(j,i);
// System.out.print(cell.getContents()+ " ");
// }
//Cell cell = rs.getCell(0,i).getContents()+ " ";
String cell1= rs.getCell(0,i).getContents()+ " ";//序号
String cell7 = rs.getCell(6,i).getContents()+ " ";//公司名称
if(cell1!=null&&!cell1.equals( " ")&&cell7!=null&&!cell7.equals( " "))//判断当前行是否为有效行 是插入否找下行
{
Company company = new Company();
company.setName(rs.getCell(0,i).getContents()+ " ");//1名称
company.setManager(rs.getCell(1,i).getContents()+ " ");//2法人
}
}
}catch(Exception e){
e.printStackTrace();
}
finally{
//操作完成时,关闭对象,释放占用的内存空间
rwb.close();
}
}
二.java读取文件大全
[Java]读取文件方法大全 1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容
public class ReadFromFile {
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 随机读取文件内容
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
* 显示输入流中还剩的字节数
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}
5、将内容追加到文件尾部
public class AppendToFile {
/**
* A方法追加文件:使用RandomAccessFile
*/
public static void appendMethodA(String fileName, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
//将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content);
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* B方法追加文件:使用FileWriter
*/
public static void appendMethodB(String fileName, String content) {
try {
//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileName = "C:/temp/newTemp.txt";
String content = "new append!";
//按方法A追加文件
AppendToFile.appendMethodA(fileName, content);
AppendToFile.appendMethodA(fileName, "append end. \n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
//按方法B追加文件
AppendToFile.appendMethodB(fileName, content);
AppendToFile.appendMethodB(fileName, "append end. \n");
//显示文件内容
ReadFromFile.readFileByLines(fileName);
}
}
三.java反射Class获得变量方法
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Rect{
double width,height,area;
public double getArea(){
area=height*width;
return area;
}
}
public class ClassInstance {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Rect rect=new Rect();
Class cs=rect.getClass();
String className=cs.getName();
Constructor[] con=cs.getDeclaredConstructors();
Field[] field=cs.getDeclaredFields();
Method[] method=cs.getDeclaredMethods();
System.out.println("类的名字:"+className);
System.out.println("类中有如下成员变量:");
for(int i=0;i<field.length;i++){
System.out.println(field[i].toString());
}
System.out.println("类中有如下方法:");
for(int j=0;j<method.length;j++){
System.out.println(method[j].toString());
}
System.out.println("类中有如下构造方法:");
for(int j=0;j<con.length;j++){
System.out.println(con[j].toString());
}
//使用类实例化一个对象
try{
Class cv=Class.forName("Rect");
Rect rec=(Rect) cv.newInstance();
rec.height=200;
rec.width=100;
System.out.println("rect的面积"+rec.getArea());
}
catch(Exception e){
e.printStackTrace();
}
}
}
四.java输入流说明
直接读取的是一串字符,不是单个,得进行转换。
1.字节数入流
public class ZhiJieInputStream {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//从键盘输入10个字符
byte[] buf=new byte[10];
String ste = null;
int num;
try{
//把数据读入到字节数组
System.in.read(buf);
//利用字节数组创建字符串
ste=new String(buf,0);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println(ste);
}
}
2.字符输入流
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CommonDivisorMultiple {
/*
* 方法一:一般解法
static int getMin=0;
static int getMax=0;
private static int getCommonMultiple(int min, int max) {
// TODO Auto-generated method stub
int getCommonMultiple;
getMax=(min>=max)?(min):(max);
getMin=(min<=max)?(min):(max);
int i=1;
while(true){
if((getMax*i)%getMin==0){
getCommonMultiple=getMax*i;
break;
}
i++;
}
return getCommonMultiple;
}
private static int getCommonDivisor(int min, int max) {
// TODO Auto-generated method stub
int getCommonDivisor = 0;
getMin=(min<max)?(min):(max);
for(int i=getMin;i>=1;i--){
if(min%i==0&& max%i==0){
getCommonDivisor=i;
break;
}
}
return getCommonDivisor;
}*/
//方法二:辗除法
private static int getCommonMultiple(int min, int max) {
// TODO Auto-generated method stub
int maxnum=Math.max(min, max);
int minmum=Math.min(min, max);
int i=1;
int t=0;
while(true){
if((maxnum*i)%minmum==0){
t=maxnum*i;
break;
}
i++;
}
return t;
}
private static int getCommonDivisor(int min, int max) {
// TODO Auto-generated method stub
int maxnum=Math.max(min, max);
int minmum=Math.min(min, max);
while(maxnum%minmum!=0){
int maxnum1=minmum;
int minnum1=maxnum%minmum;
maxnum=maxnum1;
minmum=minnum1;
}
return minmum;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String minnum,maxnum;
int min=0,max=0;
try {
BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
minnum = br.readLine();
min = Integer.parseInt(minnum);
BufferedReader br1 = new BufferedReader(new InputStreamReader(
System.in));
maxnum = br1.readLine();
max = Integer.parseInt(maxnum);
System.out.println(min + "和" + max + "的最大公约数是:"+ getCommonDivisor(min, max));
System.out.println(min + "和" + max + "的最大公倍数是:"+ getCommonMultiple(min, max));
}
catch(IOException e){
e.printStackTrace();
}
}
}
3.文本扫描器 注意:每输入一个都必须打回车
import java.util.Scanner;
public class DocumentScaner {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//定义文本扫描类Scanner类的对象
Scanner input=new Scanner(System.in);
System.out.println("输入的字符转为其他类型:");
/**
* 转换为整形:nextInt();
* 转换为字符串:next();
* 转换为单精度:nextFloat();
*/
String df=input.next();
System.out.println(df);
}
}
4.对话框输入数据
import javax.swing.JOptionPane;
public class DialogInputStream {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str;
str=JOptionPane.showInputDialog("input data:");
int num=Integer.parseInt(str);
System.out.println(num);
}
}
五.java写入文件
import java.io.*;
import java.util.*;
public class LogTest{
public static void main(String[] args)
{ File log=new File("user//log//login.log");
String newLog="UserName:Jim Green | Date:"+new Date()+" | IP:202.65.21.14";
appendLog(log,newLog);
}
public static void appendLog(File log,String newLog)
{ Scanner sc=null;
PrintWriter pw=null;
try{ if(!log.exists())//如果文件不存在,则新建.
{ File parentDir=new File(log.getParent());
if(!parentDir.exists())//如果所在目录不存在,则新建.
parentDir.mkdirs();
log.createNewFile();
}
sc=new Scanner(log);
StringBuilder sb=new StringBuilder();
while(sc.hasNextLine())//先读出旧文件内容,并暂存sb中;
{ sb.append(sc.nextLine());
sb.append("/r/n");//换行符作为间隔,扫描器读不出来,因此要自己添加.
}
sc.close();
pw=new PrintWriter(new FileWriter(log),true);
/*A.*/pw.println(sb.toString());
//,写入旧文件内容.
/*B.*/
pw.println(newLog);
//写入新日志.
/* * 如果先写入A,最近日志在文件最后. * 如是先写入B,最近日志在文件最前. */
pw.close();
}
catch(IOException ex)
{ ex.printStackTrace();
}
}
}
就是如何不覆盖的写入一个txt文件,不要把原来的内容覆盖掉,要加个什么定位语句,最好在下面的基础上加上。给高分啊!
FileWriter fileWriter=new FileWriter("c:\\Result.txt");
int [] a=new int[]{11112,222,333,444,555,666};
for (int i = 0; i < a.length; i++) {
fileWriter.write(String.valueOf(a[i])+" ");
}
fileWriter.flush();
fileWriter.close();
或者这个
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("c:\\Result.txt")));
writer.write("\"101\",\"英语\",\"english\",\"100001\"\r\n");
writer.close();
}catch(Exception e){
}
用另一个构造方法
FileWriter fileWriter=new FileWriter("c:\\Result.txt", true); // true代表追加
同理
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("c:\\Result.txt"), true));