需要一份500行的java程序,期末大作业,最好带详细注释。

需要一份500行的java程序,期末大作业,最好带详细注释。,第1张

Java生成CSV文件简单 *** 作实例

CSV是逗号分隔文件(Comma Separated Values)的首字母英文缩写,是一种用来存储数据的纯文本格式,通常用于电子表格或数据库软件。在 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())){

//避免:身份z号码 ,读取时变换为科学记数 - 解决办法:加 \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/csvcharset=GBK")

response.setHeader("Content-Disposition", "attachmentfilename="

+ 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 = 0i <files.lengthi++) {

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 = 0i <files.lengthi++) {

if (files[i].isFile()) {

if (files[i].getName().equals(fileName)) {

files[i].delete()

return

}

}

}

}

}

@SuppressWarnings({ "unchecked", "rawtypes" })

@Test

public void createFileTest() {

List exportData = new ArrayList<Map>()

Map row1 = new LinkedHashMap<String, String>()

row1.put("1", "11")

row1.put("2", "12")

row1.put("3", "13")

row1.put("4", "14")

exportData.add(row1)

row1 = new LinkedHashMap<String, 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中打开展示科学记数问题。

贪吃蛇游戏 望采纳

import java.awt.Button

import java.awt.Color

import java.awt.GridLayout

import java.awt.Point

import java.awt.event.KeyEvent

import java.awt.event.KeyListener

import java.util.*

import javax.swing.JFrame

import javax.swing.JOptionPane

public class Snake extends JFrame implements KeyListener{

int Count=0

Button[][] grid = new Button[20][20]

ArrayList<Point>snake_list=new ArrayList<Point>()

Point bean=new Point(-1,-1)//保存随机豆子【坐标】

int Direction = 1//方向标志 1:上2:下 3:左 4:右

//构造方法

public Snake()

{

//窗体初始化

this.setBounds(400,300,390,395)

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

GridLayout f=new GridLayout(20,20)

this.getContentPane().setBackground(Color.gray)

this.setLayout(f)

//初始化20*20个按钮

for(int i=0i<20i++)

for(int j=0j<20j++)

{

grid[i][j]=new Button()

this.add(grid[i][j])

grid[i][j].setVisible(false)

grid[i][j].addKeyListener(this)

grid[i][j].setBackground(Color.blue)

}

//蛇体初始化

grid[10][10].setVisible(true)

grid[11][10].setVisible(true)

grid[12][10].setVisible(true)

grid[13][10].setVisible(true)

grid[14][10].setVisible(true)

//在动态数组中保存蛇体按钮坐毁歼蔽标【行列】信息

snake_list.add(new Point(10,10))

snake_list.add(new Point(11,10))

snake_list.add(new Point(12,10))

snake_list.add(new Point(13,10))

snake_list.add(new Point(14,10))

this.rand_bean()

this.setTitle("总分:0")

this.setVisible(true)

}

//该方法随机一个豆子,且不在蛇体上,并使豆子可见

public void rand_bean(){

Random rd=new Random()

do{

bean.x=rd.nextInt(20)//纤州行

bean.y=rd.nextInt(20)//列

}while(snake_list.contains(bean))

grid[bean.x][bean.y].setVisible(true)

grid[bean.x][bean.y].setBackground(Color.red)

}

//判断拟增蛇头是否与自身有碰撞改含

public boolean is_cross(Point p){

boolean Flag=false

for(int i=0i<snake_list.size()i++){

if(p.equals(snake_list.get(i) )){

Flag=truebreak

}

}

return Flag

}

//判断蛇即将前进位置是否有豆子,有返回true,无返回false

public boolean isHaveBean(){

boolean Flag=false

int x=snake_list.get(0).x

int y=snake_list.get(0).y

Point p=null

if(Direction==1)p=new Point(x-1,y)

if(Direction==2)p=new Point(x+1,y)

if(Direction==3)p=new Point(x,y-1)

if(Direction==4)p=new Point(x,y+1)

if(bean.equals(p))Flag=true

return Flag

}

//前进一格

public void snake_move(){

if(isHaveBean()==true){//////////////有豆子吃

Point p=new Point(bean.x,bean.y)//【很重要,保证吃掉的是豆子的复制对象】

snake_list.add(0,p)//吃豆子

grid[p.x][p.y].setBackground(Color.blue)

this.Count++

this.setTitle("总分:"+Count)

this.rand_bean() //再产生一个豆子

}else{///////////////////无豆子吃

//取原蛇头坐标

int x=snake_list.get(0).x

int y=snake_list.get(0).y

//根据蛇头坐标推算出拟新增蛇头坐标

Point p=null

if(Direction==1)p=new Point(x-1,y)//计算出向上的新坐标

if(Direction==2)p=new Point(x+1,y)//计算出向下的新坐标

if(Direction==3)p=new Point(x,y-1)//计算出向左的新坐标

if(Direction==4)p=new Point(x,y+1)//计算出向右的新坐标

//若拟新增蛇头碰壁,或缠绕则游戏结束

if(p.x<0||p.x>19|| p.y<0||p.y>19||is_cross(p)==true){

JOptionPane.showMessageDialog(null, "游戏结束!")

System.exit(0)

}

//向蛇体增加新的蛇头坐标,并使新蛇头可见

snake_list.add(0,p)

grid[p.x][p.y].setVisible(true)

//删除原蛇尾坐标,使蛇尾不可见

int x1=snake_list.get(snake_list.size()-1).x

int y1=snake_list.get(snake_list.size()-1).y

grid[x1][y1].setVisible(false)

snake_list.remove(snake_list.size()-1)

}

}

@Override

public void keyPressed(KeyEvent e) {

if(e.getKeyCode()==KeyEvent.VK_UP &&Direction!=2) Direction=1

if(e.getKeyCode()==KeyEvent.VK_DOWN &&Direction!=1) Direction=2

if(e.getKeyCode()==KeyEvent.VK_LEFT &&Direction!=4) Direction=3

if(e.getKeyCode()==KeyEvent.VK_RIGHT &&Direction!=3) Direction=4

}

@Override

public void keyReleased(KeyEvent e) { }

@Override

public void keyTyped(KeyEvent e) { }

public static void main(String[] args) throws InterruptedException {

Snake win=new Snake()

while(true){

win.snake_move()

Thread.sleep(300)

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/12271225.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-22
下一篇2023-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存