如何在CSV中添加包含Java数据的列

时间:2018-10-19 17:38:44

标签: java opencsv

我们可以在CSV中添加新列作为最后一列,假设其中已经包含3列数据了吗?因此,此新列将稍后添加为第4列,并且每行应具有随机数。

示例

    <?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */

// array for JSON response
$response = array();

// check for required fields
if ( isset($_REQUEST["eng_name"]) && isset($_REQUEST["cls"]) && isset($_REQUEST["phone"]) && isset($_REQUEST["ic"]) && isset($_REQUEST["schoolID"]) && isset($_REQUEST["chi_name"]) && isset($_REQUEST["email"]) && isset($_REQUEST["address"]) && isset($_REQUEST["isMember"]) ) {

    $eng_name = $_REQUEST['eng_name'];
    $class = $_REQUEST['cls'];
    $phone = $_REQUEST['phone'];
    $nationalcard = $_REQUEST['ic'];
    $schoolID = $_REQUEST['schoolID'];
    $chi_name = $_REQUEST['chi_name'];
    $ID = $_REQUEST['ID'];
    $email = $_REQUEST['email'];
    $address = $_REQUEST['address'];
    $isMember = $_REQUEST['isMember'];


    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO list(eng_name, class, phone, ic, schoolID, chi_name, ID, email, address, isMember) VALUES('$eng_name', '$class', '$phone', '$nationalcard', '$schoolID', '$chi_name', '$ID', '$email', '$address', '$isMember')");

    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Entry successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred. Contact Tenent or ImJustChew";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

据我所知,这将需要首先读取csv,因为循环可能会迭代到最后一列,然后添加一个新的计算列,即写入csv。要增加值,可以是Java的Random类。但是,究竟该怎么做才是真正的问题。像样例代码会有所帮助。

代码:

Id  Name   Address     Calculated
1   John    U.K.        341679
2   Vj      Aus         467123
3   Scott   U.S.        844257

2 个答案:

答案 0 :(得分:2)

太好了,因此根据您提供的代码,看起来可能如下所示

(只是为了给您一个主意-我在没有测试的情况下即时将其写在这里...) :

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class Demo1 {
    //moved your random generator here 
    public static String getRandomNumber() {
      /* Code to generate random number  */
        String CHARS = "1234567890";
        StringBuilder random = new StringBuilder();
        Random rnd = new Random();
        while (random.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * CHARS.length());
            random.append(CHARS.charAt(index));
        }
        String finaldata = random.toString();
        return finaldata;
     }

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

        String csvFile = "C:\\MyData\\Input.csv";
        String temporaryCsvFile = "C:\\MyData\\Output_temp.csv";
        String line = "";
        String cvsSplitBy = ",";
        String newColumn = "";
        List<String> aobj = new ArrayList<String>();


  /* Code to read Csv file and split  */

        BufferedWriter writer = new BufferedWriter(new FileWriter(
                temporaryCsvFile));


        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {


            while ((line = br.readLine()) != null)  
            {
                //String[] csvData = line.split(cvsSplitBy);  
                //int arrayLength = csvData.length;  
                //actually you don't even need to split anything 
                 String newFileLine = line + cvsSplitBy  + getRandomNumber();  
                 // ... We call newLine to insert a newline character.
                  writer.write(newFileLine);
                  writer.newLine();

            }
        }
              writer.close();
              //Now delete the old file and rename the new file
              //I'll leave this to you 


    }
}

答案 1 :(得分:0)

基于@Plirkee示例代码和他的帮助,我编写了最终的工作代码。在此处共享它,以便对有类似要求的人有用。

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Random;


    public class Demo1 {

        public static String getRandomNumber() {

            String CHARS = "1234567890";
            StringBuilder random = new StringBuilder();
            Random rnd = new Random();
            while (random.length() < 18) // length of the random string.
            { 
                int index = (int) (rnd.nextFloat() * CHARS.length());
                random.append(CHARS.charAt(index));
            }
            String finaldata = random.toString();
            return finaldata;
        }

        public static void main(String[] args) throws IOException {
            File sourceCsvFile = null;
            File finalCsvFile = null;
            // String sourceCsvFileName = "";
            sourceCsvFile = new File("C:\\MyData\\Input.csv");
            finalCsvFile = new File("C:\\MyData\\Input_1.csv");
            String line = "";
            String cvsSplitBy = ",";



            BufferedWriter writer = new BufferedWriter(new FileWriter(finalCsvFile));


            try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) // read the actual Source downloaded csv file
            {
                line = br.readLine();  // read only first line
                String newFileLine = line + cvsSplitBy  + "HashValue";  // append "," and new column <HashValue>
                writer.write(newFileLine);   // will be written as first line in new csv
                writer.newLine();  //  go to next line for writing next lines


                while ((line = br.readLine()) != null)  // this loop to write data for all lines except headers
                {

                    newFileLine = line + cvsSplitBy  + getRandomNumber();  // will add random numbers for each row

                    writer.write(newFileLine);
                    writer.newLine();

                }

            }

            writer.close();



            if(finalCsvFile.exists() && finalCsvFile.length() > 0)
            {
                System.out.println("New File with HashValue column created...");
                if(sourceCsvFile.delete()) 
                { 
                    System.out.println("Old File deleted successfully..."); 
                }

                else
                { 
                    System.out.println("Failed to delete the Old file..."); 
                } 
            }

            else if (!finalCsvFile.exists())
            {
                System.out.println("New File with HashValue column not created...");
            }




        }
    }
相关问题