这个java代码有两个问题,一个是致命的,一个不是致命的,它们是什么?
这是我的密码。这是我为采访制作的一个程序,我被告知代码有一个致命的缺陷和一个较小的问题。我也找不到。这个程序有什么问题?我已经测试过了,看起来效果不错。我知道fileExists()方法有点不好,需要做更多的检查。。。但除此之外,我不确定还有什么错这个java代码有两个问题,一个是致命的,一个不是致命的,它们是什么?,java,xml,csv,Java,Xml,Csv,这是我的密码。这是我为采访制作的一个程序,我被告知代码有一个致命的缺陷和一个较小的问题。我也找不到。这个程序有什么问题?我已经测试过了,看起来效果不错。我知道fileExists()方法有点不好,需要做更多的检查。。。但除此之外,我不确定还有什么错 import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import j
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//I chose to use this library since it offers a solution to performing operations on CSV files, better than one I can provide from scratch.
import au.com.bytecode.opencsv.CSVReader;
public class csv2xml {
//Main program loop
public static void main(String[] args) {
String csvFilename;
String xmlFilename;
ArrayList<ArrayList<String>> data; //Raw unformatted data
boolean exists;
String xml; //Formated XML data
do{
System.out.println("Enter file path: ");
csvFilename = getUserInput(); //Gets filename from user
exists = fileExists(csvFilename);
if(exists){ //Checks to see if file exists
data = readFile(csvFilename); //Reads in content from CSV file
xml = toXML(data);
xmlFilename = csvFilename.split("\\.")[0]+".xml"; //Gets part of the filename before the first .
writeToFile(xml,xmlFilename);
}
else
System.out.println("Invalid file name, use full file path.");
}while(!exists);
}
//Reads a line of input from the user
//Returns: String
public static String getUserInput(){
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
return input;
}
//Checks to see if the file exists
//Arguments: String (name of file)
//Returns Boolean, true if file exists, false if it does not exist.
public static boolean fileExists(String filename){
File file = new File(filename);
if (file.exists()){
System.out.println("File exists");
return true;
}
return false;
}
//Reads content of CSV file and returns all data in a 2D array list
//Arguments: String (file name)
//Returns: ArrayList<ArrayList<String>> (A 2D arraylist containing the data from the csv file in a table format)
public static ArrayList<ArrayList<String>> readFile(String filename){
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> currentRow;
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String [] nextLine = null; // nextLine[] is an array of values in the current line
try {
while ((nextLine = reader.readNext()) != null) {
currentRow = new ArrayList<String>();
for(String s: nextLine){ //Puts data into a row in an arraylist
currentRow.add(s);
}
data.add(currentRow); //Adds row into arraylist
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
//Inserts xml tags between the data segments,rows and columns
//Arguments: ArrayList<ArrayList<String>> (csv data)
//Returns: String (data with xml tags)
public static String toXML(ArrayList<ArrayList<String>> data){
String xml = "<?xml version= \"1.0\"?>";
for(int i = 0; i < data.size(); i++){
xml += "\n<row id=\""+i+"\">\n";
for(int z = 0; z < data.get(i).size(); z++){
xml += "<column id=\""+z+"\">\n";
xml += "\t<data>";
xml += data.get(i).get(z);
xml += "</data>";
xml += "\n</column>\n";
}
xml += "</row>";
}
return xml;
}
//Writes data in the filename specified
//Arguments: String (data to write), String (filename to write data to)
public static void writeToFile(String data,String filename){
try {
String fn = filename;
File file = new File(filename);
// if file doesnt exists, then create it
if (file.exists()) {
System.out.println("File already exists, overwrite?(y/n):");
if(getUserInput().toLowerCase().equals("n")){
do{
System.out.println("Enter new file name:");
filename = getUserInput()+".xml";
file = new File(filename);
}while(!isValidName(filename));
}
}
else{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
//Check files name to make sure it is valid (found in MSDN Documentation)
//Arguments: String (filename)
//Returns: Boolean (true if filename is valid false if invalid)
public static boolean isValidName(String text)
{
Pattern pattern = Pattern.compile(
"# Match a valid Windows filename (unspecified file system). \n" +
"^ # Anchor to start of string. \n" +
"(?! # Assert filename is not: CON, PRN, \n" +
" (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" +
" CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" +
" COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" +
" ) # LPT6, LPT7, LPT8, and LPT9... \n" +
" (?:\\.[^.]*)? # followed by optional extension \n" +
" $ # and end of string \n" +
") # End negative lookahead assertion. \n" +
"[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" +
"[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" +
"$ # Anchor to end of string. ",
Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS);
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}
}
导入java.io.BufferedWriter;
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.FileReader;
导入java.io.FileWriter;
导入java.io.IOException;
导入java.util.ArrayList;
导入java.util.Scanner;
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
//我之所以选择使用这个库,是因为它提供了一个解决方案,可以对CSV文件执行操作,比我从头开始提供的更好。
导入au.com.bytecode.opencsv.CSVReader;
公共类csv2xml{
//主程序循环
公共静态void main(字符串[]args){
字符串csvFilename;
字符串xmlFilename;
ArrayList data;//未格式化的原始数据
布尔存在;
字符串xml;//格式化的xml数据
做{
System.out.println(“输入文件路径:”);
csvFilename=getUserInput();//从用户获取文件名
exists=fileExists(csvFilename);
if(exists){//检查文件是否存在
data=readFile(csvFilename);//从CSV文件中读取内容
xml=toXML(数据);
xmlFilename=csvFilename.split(“\\”)[0]+“.xml”;//在第一个文件名之前获取文件名的一部分。
writeToFile(xml,xmlFilename);
}
其他的
System.out.println(“文件名无效,使用完整文件路径”);
}当(!存在时);
}
//从用户处读取一行输入
//返回:字符串
公共静态字符串getUserInput(){
扫描仪=新的扫描仪(System.in);
字符串输入=scanner.nextLine();
返回输入;
}
//检查文件是否存在
//参数:字符串(文件名)
//返回布尔值,如果文件存在,则返回true;如果文件不存在,则返回false。
公共静态布尔文件存在(字符串文件名){
文件=新文件(文件名);
if(file.exists()){
System.out.println(“文件存在”);
返回true;
}
返回false;
}
//读取CSV文件的内容并返回二维数组列表中的所有数据
//参数:字符串(文件名)
//返回:ArrayList(以表格格式包含csv文件中的数据的二维ArrayList)
公共静态ArrayList读取文件(字符串文件名){
ArrayList数据=新的ArrayList();
ArrayList当前行;
CSVReader reader=null;
试一试{
reader=new CSVReader(新文件读取器(文件名));
}catch(filenotfounde异常){
e、 printStackTrace();
}
String[]nextLine=null;//nextLine[]是当前行中的值数组
试一试{
而((nextLine=reader.readNext())!=null){
currentRow=新的ArrayList();
对于(字符串s:nextLine){//将数据放入arraylist中的一行
currentRow.add(s);
}
data.add(currentRow);//将行添加到arraylist中
}
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回数据;
}
//在数据段、行和列之间插入xml标记
//参数:ArrayList(csv数据)
//返回:字符串(带有xml标记的数据)
公共静态字符串toXML(ArrayList数据){
字符串xml=”“;
对于(int i=0;iCSVReader reader = null;
try {
reader = new CSVReader(new FileReader(filename));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String [] nextLine = null; // nextLine[] is an array of values in the current line
try {
while ((nextLine = reader.readNext()) != null) {
currentRow = new ArrayList<String>();
for(String s: nextLine){ //Puts data into a row in an arraylist
currentRow.add(s);
}
data.add(currentRow); //Adds row into arraylist
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}