Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用opencsv读取远程.csv文件_Java_Opencsv - Fatal编程技术网

Java 使用opencsv读取远程.csv文件

Java 使用opencsv读取远程.csv文件,java,opencsv,Java,Opencsv,我已经思考了相当长的时间了。我正在尝试从下载数据。使用API时,它会为您提供一个.csv文件。我一直在看opencsv,它似乎很完美,但如果可能的话,我想避免使用它 根据,OpenCSV只能从文件读取器中读取。根据Oracle的说法,该文件必须是本地文件 是否可以在不下载的情况下使用OpenCSV从远程文件中读取?CSVReader根据获取Reader参数,因此参数不限于FileReader 要在不先保存文件的情况下使用CSVReader,可以在加载数据的流周围使用BufferedReader

我已经思考了相当长的时间了。我正在尝试从下载数据。使用API时,它会为您提供一个
.csv
文件。我一直在看opencsv,它似乎很完美,但如果可能的话,我想避免使用它

根据,OpenCSV只能从
文件读取器中读取。根据Oracle的说法,该文件必须是本地文件



是否可以在不下载的情况下使用OpenCSV从远程文件中读取?

CSVReader
根据获取
Reader
参数,因此参数不限于
FileReader

要在不先保存文件的情况下使用
CSVReader
,可以在加载数据的流周围使用
BufferedReader

URL stockURL = new URL("http://example.com/stock.csv");
BufferedReader in = new BufferedReader(new InputStreamReader(stockURL.openStream()));
CSVReader reader = new CSVReader(in);
// use reader

opencsv的实现,用于读取csv文件并保存到数据库

import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.bean.CsvBindByPosition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Column;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class FileUploadService {

    @Autowired
    private InsertCSVContentToDB csvContentToDB;


    /**
     * @param csvFileName location of the physical file.
     * @param type Employee.class
     * @param delimiter  can be , | # etc
     * @param obj    //new Employee();
     *
     *            import com.opencsv.bean.CsvBindByPosition;
     *            import lombok.Data;
     *
     *            import javax.persistence.Column;
     *
     *              @Data
     *              public class Employee {
     *
     *              @CsvBindByPosition(position = 0, required = true)
     *              @Column(name = "EMPLOYEE_NAME")
     *              private String employeeName;
     *
     *              @CsvBindByPosition(position = 1)
     *              @Column(name = "Employee_ADDRESS_1")
     *              private String employeeAddress1;
     *          }
     *
     * @param sqlQuery  query to save data to DB
     * @param noOfLineSkip make it 0(Zero) so that it should not skip any line.
     * @param auditId apart from regular column in csv we need to add more column for traking like file id or audit id
     * @return
     */
    public <T> void readCSVContentInArray(String csvFileName, Class<? extends T> type, char delimiter, Object obj,
                                                  String sqlQuery, int noOfLineSkip, Long auditId) {
        List<T> lstCsvContent = new ArrayList<>();
        Reader reader = null;
        CSVReader csv = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFileName), "utf-8"));
            log.info("Buffer Reader : " + ((BufferedReader) reader).readLine().isEmpty());
            CSVParser parser = new CSVParserBuilder().withSeparator(delimiter).withIgnoreQuotations(true).build();
            csv = new CSVReaderBuilder(reader).withSkipLines(noOfLineSkip).withCSVParser(parser).build();
            String[] nextLine;
            int size = 0;
            int chunkSize = 10000;
            Class params[] = { Long.class };
            Object paramsObj[] = { auditId };
            long rowNumber = 0;
            Field field[] = type.getDeclaredFields();
            while ((nextLine = csv.readNext()) != null) {
                rowNumber++;
                try {

                    obj = type.newInstance();

                    for (Field f : field) {
                        if(!f.isSynthetic()){
                            f.setAccessible(true);
                            Annotation ann[] = f.getDeclaredAnnotations();
                            CsvBindByPosition csv1 = (CsvBindByPosition) ann[0];
                            Column c = (Column)ann[1];

                            try {
                                if (csv1.position() < nextLine.length) {
                                    if (csv1.required() && (nextLine[csv1.position()] == null
                                            || nextLine[csv1.position()].trim().isEmpty())) {
                                        String message = "Mandatory field is missing in row: " + rowNumber;
                                        log.info("null value in " + rowNumber + ", " + csv1.position());
                                        System.out.println(message);

                                    }

                                    if (f.getType().equals(String.class)) {
                                        f.set(obj, nextLine[csv1.position()]);

                                    }
                                    if (f.getType().equals(Boolean.class)) {
                                        f.set(obj, nextLine[csv1.position()]);

                                    }
                                    if (f.getType().equals(Integer.class)) {
                                        f.set(obj, Integer.parseInt(nextLine[csv1.position()]));

                                    }
                                    if (f.getType().equals(Long.class)) {
                                        f.set(obj, Long.parseLong(nextLine[csv1.position()]));
                                    }
                                    if (f.getType().equals(Double.class) && null!=nextLine[csv1.position()] && !nextLine[csv1.position()].trim().isEmpty()  ) {
                                        f.set(obj, Double.parseDouble(nextLine[csv1.position()]));

                                    }if(f.getType().equals(Double.class) && ((nextLine[csv1.position()]==null) || nextLine[csv1.position()].isEmpty())){
                                        f.set(obj, new Double("0.0"));
                                    }
                                    if (f.getType().equals(Date.class)) {
                                        f.set(obj, nextLine[csv1.position()]);
                                    }
                                }
                            } catch (Exception fttEx) {
                                log.info("Exception when parsing the file: " + fttEx.getMessage());
                                System.out.println(fttEx.getMessage());
                            }
                        }
                    }
                    lstCsvContent.add((T) obj);
                    if (lstCsvContent.size() > chunkSize) {
                        size = size + lstCsvContent.size();
                        //write code to save to data base of file system in chunk.
                        lstCsvContent = null;
                        lstCsvContent = new ArrayList<>();
                    }

                } catch (Exception ex) {
                    log.info("Exception: " + ex.getMessage());
                }

            }
            //write code to save list into DB or file system
            System.out.println(lstCsvContent);
        } catch (Exception ex) {
            log.info("Exception:::::::: " + ex.getMessage());

        } finally {
            try {
                if (csv != null) {
                    csv.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ioe) {

                log.info("Exception when closing the file: " + ioe.getMessage());
            }
        }
        log.info("File Processed successfully: ");
    }


}
导入com.opencsv.CSVParser;
导入com.opencsv.CSVParserBuilder;
导入com.opencsv.CSVReader;
导入com.opencsv.CSVReaderBuilder;
导入com.opencsv.bean.CsvBindByPosition;
导入lombok.extern.slf4j.slf4j;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Service;
导入javax.persistence.Column;
导入java.io.*;
导入java.lang.annotation.annotation;
导入java.lang.reflect.Field;
导入java.util.ArrayList;
导入java.util.Date;
导入java.util.List;
@服务
@Slf4j
公共类文件上载服务{
@自动连线
私有insertcscscontenttodb csvContentToDB;
/**
*@param csvFileName物理文件的位置。
*@param type Employee.class
*@param分隔符可以是、|#等
*@param obj//new Employee();
*
*导入com.opencsv.bean.CsvBindByPosition;
*导入龙目数据;
*
*导入javax.persistence.Column;
*
*@数据
*公营雇员{
*
*@CsvBindByPosition(position=0,required=true)
*@Column(name=“EMPLOYEE\u name”)
*私有字符串employeeName;
*
*@CsvBindByPosition(position=1)
*@Column(name=“Employee\u ADDRESS\u 1”)
*私有字符串employeeAddress1;
*          }
*
*@param sqlQuery将数据保存到数据库
*@param noOfLineSkip将其设为0(零),这样它就不会跳过任何一行。
*@param audited除了csv中的常规列之外,我们还需要添加更多列用于跟踪,如文件id或审核id
*@返回
*/

public void readCSVContentInArray(字符串csvFileName,class实际上,它使用了一个通用读取器,其中有几个实现。Aka,您不必使用文件读取器。嗯,
StockURL
!=
StockURL
@BhargavRao感谢您注意到了这一点,但一般来说,您可以自己编辑它,这样做!是的,我通常在出现错误时都会编辑它不是在代码中。但这里的输入错误是在代码中。作为一名Java学习者,当我看到:D…这就是我不想编辑它并留下评论的原因。感谢编辑它。CheersHow要向url添加身份验证吗?比如用户名和密码?@SwapnilGangrade你需要使用Java的buil之类的东西发布你的参数t-in
HttpURLConnection
或其他库。有关设置请求的示例,请参阅,该请求提供一个生成的输入流,您可以在我的回答中用作读取器。