
正文
java500行代码删除的简单介绍
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
需要一份500行的java程序,期末大作业,最好带详细注释。
Java生成CSV文件简单操作实例
CSV是逗号分隔文件(Comma Separated Values)java500行代码删除的首字母英文缩写java500行代码删除,是一种用来存储数据的纯文本格式,通常用于电子表格或数据库软件。在 CSV文件中,数据“栏”以逗号分隔,可允许程序通过读取文件为数据重新创建正确的栏结构,并在每次遇到逗号时开始新的一栏。如:
123 1,张三,男2,李四,男3,小红,女
Java生成CSV文件(创建与导出封装类)
package com.yph.omp.common.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;
/**
* Java生成CSV文件
*/
public class CSVUtil {
/**
* 生成为CVS文件
*
* @param exportData
* 源数据List
* @param map
* csv文件的列表头map
* @param outPutPath
* 文件路径
* @param fileName
* 文件名称
* @return
*/
@SuppressWarnings("rawtypes")
public static File createCSVFile(List exportData, LinkedHashMap map,
String outPutPath, String fileName) {
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
File file = new File(outPutPath);
if (!file.exists()) {
file.mkdir();
}
// 定义文件名格式并创建
csvFile = File.createTempFile(fileName, ".csv",
new File(outPutPath));
// UTF-8使正确读取分隔符","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(csvFile), "GBK"), 1024);
// 写入文件头部
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
.hasNext();) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
csvFileOutputStream
.write("\"" + (String) propertyEntry.getValue() != null ? (String) propertyEntry
.getValue() : "" + "\"");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();
// 写入文件内容
for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
Object row = (Object) iterator.next();
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
.hasNext();) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
/*-------------------------------*/
//以下部分根据不同业务做出相应的更改
StringBuilder sbContext = new StringBuilder("");
if (null != BeanUtils.getProperty(row,(String) propertyEntry.getKey())) {
if("证件号码".equals(propertyEntry.getValue())){
//避免:身份证号码 ,读取时变换为科学记数 - 解决办法:加 \t(用Excel打开时,证件号码超过15位后会自动默认科学记数)
sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t");
}else{
sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()));
}
}
csvFileOutputStream.write(sbContext.toString());
/*-------------------------------*/
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
if (iterator.hasNext()) {
csvFileOutputStream.newLine();
}
}
csvFileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
/**
* 下载文件
*
* @param response
* @param csvFilePath
* 文件路径
* @param fileName
* 文件名称
* @throws IOException
*/
public static void exportFile(HttpServletRequest request,
HttpServletResponse response, String csvFilePath, String fileName)
throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/csv;charset=GBK");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(fileName.getBytes("GB2312"), "ISO8859-1"));
InputStream in = null;
try {
in = new FileInputStream(csvFilePath);
int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer)) 0) {
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e1) {
System.out.println(e1);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
}
}
/**
* 删除该目录filePath下的所有文件
*
* @param filePath
* 文件目录路径
*/
public static void deleteFiles(String filePath) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i files.length; i++) {
if (files[i].isFile()) {
files[i].delete();
}
}
}
}
/**
* 删除单个文件
*
* @param filePath
* 文件目录路径
* @param fileName
* 文件名称
*/
public static void deleteFile(String filePath, String fileName) {
File file = new File(filePath);
if (file.exists()) {
File[] files = file.listFiles();
for (int i = 0; i files.length; i++) {
if (files[i].isFile()) {
if (files[i].getName().equals(fileName)) {
files[i].delete();
return;
}
}
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void createFileTest() {
List exportData = new ArrayListMap();
Map row1 = new LinkedHashMapString, String();
row1.put("1", "11");
row1.put("2", "12");
row1.put("3", "13");
row1.put("4", "14");
exportData.add(row1);
row1 = new LinkedHashMapString, String();
row1.put("1", "21");
row1.put("2", "22");
row1.put("3", "23");
row1.put("4", "24");
exportData.add(row1);
LinkedHashMap map = new LinkedHashMap();
map.put("1", "第一列");
map.put("2", "第二列");
map.put("3", "第三列");
map.put("4", "第四列");
String path = "d:/export";
String fileName = "文件导出";
File file = CSVUtil.createCSVFile(exportData, map, path, fileName);
String fileNameNew = file.getName();
String pathNew = file.getPath();
System.out.println("文件名称:" + fileNameNew );
System.out.println("文件路径:" + pathNew );
}
}
//注:BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t" ,只为解决数字格式超过15位后,在Excel中打开展示科学记数问题。
相关问答
Q1: Java中怎样实现批量删除操作
本文是记录Java中实现批量删除操纵(Java对数据库进行事务处置),在开始之前先来看上面这样的一个页面图:
上面这张图片表现的是从数据库中查询出的出租信息,信息中进行了分页处置,然后每行的后面提供了一个复选按钮和对应的一个删除操纵,可以选中多个进行操纵,这里主要是进行删除操纵。在执行删除操纵之前先要选中对应的行信息,点击删除选中按钮进行删除。当进行多条信息删除的时候,需要使用java的事务处置机制对数据库进行删除,也就是说删除的时候如果选中的要删除的说有信息其中一条没有成功删除的话,那么就都不删除。
现在是在java中对数据库实现这一操纵,我们可看上面的代码,它实现了对数据库的批量删除操纵,代码如下:
public Connection con=null;
public PreparedStatement pstmt=null;
/**
* 失掉连接对象
*/
public void getConnection(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/zufang?user=rootpassword=rootuseUnicode=truecharacterEncoding=GB2312";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,"root","root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/** * 批量删除信息表中的信息 * @param sql * @param param * @return */ public boolean updateBatchDel(String sql,String[] param){ boolean flag = false; getConnection(); try { con.setAutoCommit(false); pstmt = con.prepareStatement(sql); for(int i =0 ;iparam.length;i++){ pstmt.setString(1,param[i].trim()); pstmt.addBatch(); } pstmt.executeBatch(); //批量执行 con.commit();//提交事务 flag = true; } catch (SQLException e) { try { con.rollback(); //进行事务回滚 } catch (SQLException ex) { ex.printStackTrace(); } }finally { closeAll(null,pstmt,con); } return flag; }
当然上面是进行批量删除,如果我们只删除一条信息的话也可以使用独自的删除方法,即是:点击删除,当然上面的方法也是可以完成的,还是再看一下吧:
/**
* 删除某条求租表中的信息
* @param id 删除信息的id
* @return 如果删除成功,返回true;否则返回false
*/
public boolean delQiuZu(String id){
boolean flag=false;
String sql="delete from qiuzhu where id=?";
String[] param={id};
flag=bd.updateDate(sql, param);
return flag;
}
控制器servlet中的处置操纵代码如下:
package com.sxt.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sxt.biz.ChuZuBiz;
import com.sxt.biz.PageBiz;
import com.sxt.biz.QiuZuBiz;
public class OutDateQiuzuServlet extends HttpServlet {
QiuZuBiz qzb=new QiuZuBiz();
PageBiz pb=new PageBiz();
int pagesize=10;
boolean flag=true;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312");
int countpage=pb.getOutDatePageCountQiuzu(pagesize);
request.setAttribute("countpage", countpage);
String nowpage=request.getParameter("nowpage");
String id=request.getParameter("id");
PrintWriter out = response.getWriter();
String command = request.getParameter("command");
if ("del".equals(command)) {
String[] qiuzuIds = request.getParameterValues("selectFlag");
boolean flag = qzb.delQiuzuMany(qiuzuIds);
if(flag){
out.print("scriptalert('删除成功!');/script");
}else{
out.print("scriptalert('删除失败!');/script");
}
}
if(nowpage==null){
nowpage="1";
}
if(Integer.valueOf(nowpage)=0){
nowpage="1";
}
if(Integer.valueOf(nowpage)countpage){
nowpage=countpage+"";
}
if(id!=null){
flag=qzb.delQiuZu(id);
}
request.setAttribute("currentpage", nowpage);
List list=qzb.getOutDateQiuZuInfo(Integer.valueOf(nowpage), pagesize);
request.setAttribute("list1", list);
if(flag){
request.getRequestDispatcher("admin/OutDateQiuzu.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
上面是对数据库的操纵代码,上面看一下页面中怎样实现的,代码如下:
每日一道理
灯,带有一种明亮的光,每当深夜来临,是它陪伴着你,如此默默无闻。它是平凡的,外表华丽与否,那都是一样的,珍珠点缀,水晶加饰的灯它只能用以装饰,来满足人们的虚荣心,比起这,普普通通的日光灯是幸运的,因为它照明的本性没有改变,如同生活中的一部分人平平凡凡却实实在在。
%@ page language="java" import="java.util.*" pageEncoding="GB18030"%
%@ taglib uri="#" prefix="c" %
html
head
titlehouse/title
script type="text/javascript"
//删除用户控制
function deleteSelect() {
var select = document.getElementsByName("selectFlag");
var flag = false;
for (var i=0; iselect.length; i++) {
if (select[i].checked) {
flag = true;
break;
}
}
if (!flag) {
alert("请选择需要删除的过期求租信息!");
return;
}
if (window.confirm("确认要删除过期的求租信息吗?")) {
with (document.getElementById("userform")) {
action="OutDateQiuzuServlet?command=del";
method="post";
submit();
}
}
}
//全选/反选操纵
function checkAll(ifAll) {
var select = document.getElementsByName("selectFlag");
for(var i = 0;iselect.length;i++){
select[i].checked = ifAll.checked;
}
}
/script
/head
link rel="stylesheet" href="./skin/css/lianjie.css" type="text/css" /
body
form name="userform" action="ChuzuServlet" method="get"
table width="1000" height="80" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"
tr
td height="40" align="center" bgcolor="#F1F1F1"font color="#FF0000"b已过期的求租信息/b/font/td
/tr
tr
td align="left"
input name="btnDelete" class="button1" type="button"
id="btnDelete" value="删除选中" onClick="deleteSelect()"
/td
/tr
/table
table width="1000" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC" style="word-break:break-all;"
tr align="center"
td width="15%" height="25" bgcolor="#F1F1F1"font size="3" input type="checkbox" name="ifAll" title="全选/反选" onClick="checkAll(this)" checked="checked"//font/td
td width="10%" bgcolor="#F1F1F1"font size="3"期望区域/font/td
td width="15%" bgcolor="#F1F1F1"font size="3"装修水平/font/td
td width="10%" bgcolor="#F1F1F1"font size="3"房型/font/td
td width="10%" bgcolor="#F1F1F1"font size="3"面积(平米)/font/td
td width="10%" bgcolor="#F1F1F1"font size="3"价格(元)/font/td
td width="10%" bgcolor="#F1F1F1"font size="3"添加日期/font/td
td width="10%" bgcolor="#F1F1F1"font size="3"有效天数/font/td
td width="10%" bgcolor="#F1F1F1"font size="3"残余天数/font/td
/tr
c:choose
c:when test="${empty list1}"
trtd colspan="8" align="center"font color="red"还没有过期的求租信息!/font/td/tr
/c:when
c:otherwise
c:forEach var="qiuzu" items="${list1}"
tr
td height="25" align="center" bgcolor="#FFFFFF"input type="checkbox" name="selectFlag" value="${qiuzu.id}" checked="checked"//font
a href="javascript:if(confirm('确定要删除这条过期的求租信息吗?')){location.href='OutDateQiuzuServlet?id=${qiuzu.id}'}" style="COLOR: #0000ff;font-size:14px; TEXT-DECORATION:none;"font size="2"删除/font/a/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.qwqy}/font/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.zxcd}/font/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.hx}/font/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.jzmj}/font/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.zj}/font/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.addDate}/font/td
td align="center" bgcolor="#FFFFFF"font size="2"${qiuzu.yxts}/font/td
td align="center" bgcolor="#FFFFFF"font size="2" color="red"${qiuzu.syts}/font/td
/tr
/c:forEach
/c:otherwise
/c:choose
/table
/p
table width="300" align="center"
tr
td align="center"font size="2"共${countpage}页/font/td
td align="center"font size="2"${currentpage}/${countpage}页/font/td
td align="center"a href="OutDateQiuzuServlet?nowpage=${1}"font size="2"首页/font/a/td
td align="center"a href="OutDateQiuzuServlet?nowpage=${currentpage-1}"font size="2"上一页/font/a/td
td align="center"a href="OutDateQiuzuServlet?nowpage=${currentpage+1}"font size="2"下一页/font/a/td
td align="center"a href="OutDateQiuzuServlet?nowpage=${countpage}"font size="2"尾页/font/a/td
/tr
/table
/form
/body
/html
Q2: Java中怎样实现批量删除操作?
进行编写编程代码就能实现批量删除操作。
具体代码如下java500行代码删除:
[java] SPAN style="WHITE-SPACE: pre" /SPANpublic Connection con=null;
public PreparedStatement pstmt=null;
/**
* 得到连接对象
*/
public void getConnection(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/zufang?
user=rootpassword=rootuseUnicode=truecharacterEncoding=GB2312";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,"root","root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection con=null;
public PreparedStatement pstmt=null;
/**
* 得到连接对象
*/
public void getConnection(){
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/zufang?
user=rootpassword=rootuseUnicode=truecharacterEncoding=GB2312";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,"root","root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
[java] SPAN style="WHITE-SPACE: pre" /SPAN/**
* 批量删除信息表中java500行代码删除的信息
* @param sql
* @param param
* @return
*/
public boolean updateBatchDel(String sql,String[] param){
boolean flag = false;
getConnection();
try {
con.setAutoCommit(false);
pstmt = con.prepareStatement(sql);
for(int i =0 ;iparam.length;i++){
pstmt.setString(1,param[i].trim());
pstmt.addBatch();
}
pstmt.executeBatch(); //批量执行
con.commit();//提交事务
flag = true;
} catch (SQLException e) {
try {
con.rollback(); //进行事务回滚
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
closeAll(null,pstmt,con);
}
return flag;
}
/**
* 批量删除信息表中java500行代码删除的信息
* @param sql
* @param param
* @return
*/
public boolean updateBatchDel(String sql,String[] param){
boolean flag = false;
getConnection();
try {
con.setAutoCommit(false);
pstmt = con.prepareStatement(sql);
for(int i =0 ;iparam.length;i++){
pstmt.setString(1,param[i].trim());
pstmt.addBatch();
}
pstmt.executeBatch(); //批量执行
con.commit();//提交事务
flag = true;
} catch (SQLException e) {
try {
con.rollback(); //进行事务回滚
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
closeAll(null,pstmt,con);
}
return flag;
上面是进行批量删除的编程码。
Q3: java怎么实现表格的行删除
java中表格的删除是通过事件监控来实现的,示例代码如下:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
//维护表格
public class JTableDefaultTableModelTest extends JFrame{
private DefaultTableModel tableModel; //表格模型对象
private JTable table;
private JTextField aTextField;
private JTextField bTextField;
public JTableDefaultTableModelTest()
{
super();
setTitle("表格");
setBounds(100,100,500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnNames = {"A","B"}; //列名
String [][]tableVales={{"A1","B1"},{"A2","B2"},{"A3","B3"},{"A4","B4"},{"A5","B5"}}; //数据
tableModel = new DefaultTableModel(tableVales,columnNames);
table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table); //支持滚动
getContentPane().add(scrollPane,BorderLayout.CENTER);
//jdk1.6
//排序:
//table.setRowSorter(new TableRowSorter(tableModel));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //单选
table.addMouseListener(new MouseAdapter(){ //鼠标事件
public void mouseClicked(MouseEvent e){
int selectedRow = table.getSelectedRow(); //获得选中行索引
Object oa = tableModel.getValueAt(selectedRow, 0);
Object ob = tableModel.getValueAt(selectedRow, 1);
aTextField.setText(oa.toString()); //给文本框赋值
bTextField.setText(ob.toString());
}
});
scrollPane.setViewportView(table);
final JPanel panel = new JPanel();
getContentPane().add(panel,BorderLayout.SOUTH);
panel.add(new JLabel("A: "));
aTextField = new JTextField("A4",10);
panel.add(aTextField);
panel.add(new JLabel("B: "));
bTextField = new JTextField("B4",10);
panel.add(bTextField);
final JButton addButton = new JButton("添加"); //添加按钮
addButton.addActionListener(new ActionListener(){//添加事件
public void actionPerformed(ActionEvent e){
String []rowValues = {aTextField.getText(),bTextField.getText()};
tableModel.addRow(rowValues); //添加一行
int rowCount = table.getRowCount() +1; //行数加上1
aTextField.setText("A"+rowCount);
bTextField.setText("B"+rowCount);
}
});
panel.add(addButton);
final JButton updateButton = new JButton("修改"); //修改按钮
updateButton.addActionListener(new ActionListener(){//添加事件
public void actionPerformed(ActionEvent e){
int selectedRow = table.getSelectedRow();//获得选中行的索引
if(selectedRow!= -1) //是否存在选中行
{
//修改指定的值:
tableModel.setValueAt(aTextField.getText(), selectedRow, 0);
tableModel.setValueAt(bTextField.getText(), selectedRow, 1);
//table.setValueAt(arg0, arg1, arg2)
}
}
});
panel.add(updateButton);
final JButton delButton = new JButton("删除");
delButton.addActionListener(new ActionListener(){//添加事件
public void actionPerformed(ActionEvent e){
int selectedRow = table.getSelectedRow();//获得选中行的索引
if(selectedRow!=-1) //存在选中行
{
tableModel.removeRow(selectedRow); //删除行
}
}
});
panel.add(delButton);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JTableDefaultTableModelTest jTableDefaultTableModelTest = new JTableDefaultTableModelTest();
jTableDefaultTableModelTest.setVisible(true);
}
}
关于java500行代码删除和的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。







