这是我的代码。这是我为面试制作的程序,有人告诉我代码有一个致命缺陷,还有一个小问题。我也找不到。程序有什么问题?我已经测试过了,它似乎工作正常。我知道 fileExists() 方法有点糟糕,需要做更多检查......但除此之外,我不确定还有什么问题......
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;
}
}