encode special character java - java

I'm trying to fix a bug in the code I wrote which convert a srt file to dxfp.xml. it works fine but when there is a special character such as an ampersand it throws an java.lang.NumberFormatException error. I tried to use the StringEscapeUtils function from apache commons to solve it. Can someone explain to me what it is I am missing here? thanks in advance!
public class SRT_TO_DFXP_Converter {
File input_file;
File output_file;
ArrayList<CaptionLine> node_list;
public SRT_TO_DFXP_Converter(File input_file, File output_file) {
this.input_file = input_file;
this.output_file = output_file;
this.node_list = new ArrayList<CaptionLine>();
}
class CaptionLine {
int line_num;
String begin_time;
String end_time;
ArrayList<String> content;
public CaptionLine(int line_num, String begin_time, String end_time,
ArrayList<String> content) {
this.line_num = line_num;
this.end_time = end_time;
this.begin_time = begin_time;
this.content = content;
}
public String toString() {
return (line_num + ": " + begin_time + " --> " + end_time + "\n" + content);
}
}
private void readSRT() {
BufferedReader bis = null;
FileReader fis = null;
String line = null;
CaptionLine node;
Integer line_num;
String[] time_split;
String begin_time;
String end_time;
try {
fis = new FileReader(input_file);
bis = new BufferedReader(fis);
do {
line = bis.readLine();
line_num = Integer.valueOf(line);
line = bis.readLine();
time_split = line.split(" --> ");
begin_time = time_split[0];
begin_time = begin_time.replace(',', '.');
end_time = time_split[1];
end_time.replace(',', '.');
ArrayList<String> content = new ArrayList<String>();
while (((line = bis.readLine()) != null)
&& (!(line.trim().equals("")))) {
content.add(StringEscapeUtils.escapeJava(line));
//if (StringUtils.isEmpty(line)) break;
}
node = new CaptionLine(line_num, begin_time, end_time, content);
node_list.add(node);
} while (line != null);
} catch (Exception e) {
System.out.println(e);
}
finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private String convertToXML() {
StringBuffer dfxp = new StringBuffer();
dfxp.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\">\n\t<head>\n\t\t<styling>\n\t\t\t<style id=\"1\" tts:backgroundColor=\"black\" tts:fontFamily=\"Arial\" tts:fontSize=\"14\" tts:color=\"white\" tts:textAlign=\"center\" tts:fontStyle=\"Plain\" />\n\t\t</styling>\n\t</head>\n\t<body>\n\t<div xml:lang=\"en\" style=\"default\">\n\t\t<div xml:lang=\"en\">\n");
for (int i = 0; i < node_list.size(); i++) {
dfxp.append("\t\t\t<p begin=\"" + node_list.get(i).begin_time + "\" ")
.append("end=\"" + node_list.get(i).end_time
+ "\" style=\"1\">");
for (int k = 0; k < node_list.get(i).content.size(); k++) {
dfxp.append("" + node_list.get(i).content.get(k));
}
dfxp.append("</p>\n");
}
dfxp.append("\t\t</div>\n\t</body>\n</tt>\n");
return dfxp.toString();
}
private void writeXML(String dfxp) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output_file));
out.write(dfxp);
out.close();
} catch (IOException e) {
System.out.println("Error Writing To File:"+ input_file +'\n');
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
if ((args.length < 2) || (args[1].equals("-h"))) {
System.out.println("\n<--- SRT to DFXP Converter Usage --->");
System.out
.println("Conversion: java -jar SRT_TO_DFXP.jar <input_file> <output_file> [-d]");
System.out
.println("Conversion REQUIRES a input file and output file");
System.out.println("[-d] Will Display XML Generated In Console");
System.out.println("Help: java -jar SRT_TO_DFXP.jar -h");
} else if (!(new File(args[0]).exists())) {
System.out.println("Error: Input SubScript File Does Not Exist\n");
} else {
SRT_TO_DFXP_Converter converter = new SRT_TO_DFXP_Converter(
new File(args[0]), new File(args[1]));
converter.readSRT();
String dfxp = converter.convertToXML();
if ((args.length == 3) && (args[2].equals("-d")))
System.out.println("\n" + dfxp + "\n");
converter.writeXML(dfxp);
System.out.println("Conversion Complete");
}
}
here's part of the srt file that it is throwing an error when exported and run as a jar file.
1
00:20:43,133 --> 00:20:50,599
literature and paper by Liversmith & Newman, and I think the point is well made that a host of factors

Related

JSchException Cannot find message

I want to know some of the reasons that can cause below exception. I am unable to find this message Cannot find message in jsch-0.1.54.jar. There exists some straight forward messages like file not found and others that make sense. But I need more information about this one so that I can reach to the root cause.
SftpException while running get ---> 2: Cannot find message [/destination/file.txt]
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2289)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1741)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1758)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:786)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:750)
at com.iyi.ftp.SFTP.get(SFTP.java:99)
Here is my calling method.
public boolean get(final String remoteFile, final String localFile) throws JSchException {
Vector connection = null;
Session session = null;
ChannelSftp c = null;
boolean status = false;
try {
connection = this.connect();
session = connection.get(0);
c = connection.get(1);
c.get(remoteFile, localFile);
status = true;
}
catch (JSchException e) {
SFTP.LGR.warn((Object)("JSchException in SFTP::get() ---> " + FTPFactory.getStackTrace((Throwable)e)));
throw e;
}
catch (SftpException e2) {
SFTP.LGR.warn((Object)("SftpException while running get ---> " + FTPFactory.getStackTrace((Throwable)e2)));
throw new JSchException(e2.getMessage());
}
catch (CredentialDecryptionException e3) {
SFTP.LGR.error((Object)"##CredentialDecryptionException##", (Throwable)e3);
throw new JSchException(e3.getMessage(), (Throwable)e3);
}
finally {
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
}
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
return status;
}
These methods are fetched from jsch-0.1.54.jar which is an open source utility.
public void get(String src, String dst, final SftpProgressMonitor monitor, final int mode) throws SftpException {
boolean _dstExist = false;
String _dst = null;
try {
((MyPipedInputStream)this.io_in).updateReadSide();
src = this.remoteAbsolutePath(src);
dst = this.localAbsolutePath(dst);
final Vector v = this.glob_remote(src);
final int vsize = v.size();
if (vsize == 0) {
throw new SftpException(2, "No such file");
}
final File dstFile = new File(dst);
final boolean isDstDir = dstFile.isDirectory();
StringBuffer dstsb = null;
if (isDstDir) {
if (!dst.endsWith(ChannelSftp.file_separator)) {
dst += ChannelSftp.file_separator;
}
dstsb = new StringBuffer(dst);
}
else if (vsize > 1) {
throw new SftpException(4, "Copying multiple files, but destination is missing or a file.");
}
for (int j = 0; j < vsize; ++j) {
final String _src = v.elementAt(j);
final SftpATTRS attr = this._stat(_src);
if (attr.isDir()) {
throw new SftpException(4, "not supported to get directory " + _src);
}
_dst = null;
if (isDstDir) {
final int i = _src.lastIndexOf(47);
if (i == -1) {
dstsb.append(_src);
}
else {
dstsb.append(_src.substring(i + 1));
}
_dst = dstsb.toString();
if (_dst.indexOf("..") != -1) {
final String dstc = new File(dst).getCanonicalPath();
final String _dstc = new File(_dst).getCanonicalPath();
if (_dstc.length() <= dstc.length() || !_dstc.substring(0, dstc.length() + 1).equals(dstc + ChannelSftp.file_separator)) {
throw new SftpException(4, "writing to an unexpected file " + _src);
}
}
dstsb.delete(dst.length(), _dst.length());
}
else {
_dst = dst;
}
final File _dstFile = new File(_dst);
if (mode == 1) {
final long size_of_src = attr.getSize();
final long size_of_dst = _dstFile.length();
if (size_of_dst > size_of_src) {
throw new SftpException(4, "failed to resume for " + _dst);
}
if (size_of_dst == size_of_src) {
return;
}
}
if (monitor != null) {
monitor.init(1, _src, _dst, attr.getSize());
if (mode == 1) {
monitor.count(_dstFile.length());
}
}
FileOutputStream fos = null;
_dstExist = _dstFile.exists();
try {
if (mode == 0) {
fos = new FileOutputStream(_dst);
}
else {
fos = new FileOutputStream(_dst, true);
}
this._get(_src, fos, monitor, mode, new File(_dst).length());
}
finally {
if (fos != null) {
fos.close();
}
}
}
}
catch (Exception e) {
if (!_dstExist && _dst != null) {
final File _dstFile2 = new File(_dst);
if (_dstFile2.exists() && _dstFile2.length() == 0L) {
_dstFile2.delete();
}
}
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
private SftpATTRS _stat(final byte[] path) throws SftpException {
try {
this.sendSTAT(path);
Header header = new Header();
header = this.header(this.buf, header);
final int length = header.length;
final int type = header.type;
this.fill(this.buf, length);
if (type != 105) {
if (type == 101) {
final int i = this.buf.getInt();
this.throwStatusError(this.buf, i);
}
throw new SftpException(4, "");
}
final SftpATTRS attr = SftpATTRS.getATTR(this.buf);
return attr;
}
catch (Exception e) {
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
The error message comes from your server. It's indeed quite strange message, but I assume that it's some custom SFTP server that deals with some "messages" rather than plain files.
So the message basically translates to "Cannot find file" error of a traditional SFTP server. Even the error code 2 (SSH_FX_NO_SUCH_FILE) supports that.
Your path in remoteFile is probably wrong.

java, sonar, Cyclomatic Complexity

can anyone help me to reduce cylomatic complexity for below method upto 10..also considering no nesting of if else is allow as it will also cause sonar issue.
It will be great help for me
private void processIntransitFile(String fileName) {
if (StringUtils.isNotBlank(fileName))
return;
// read Intransit folder and do the processing on these files
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(intransitDir + fileName))) {
TokenRangeDTO tokenRangeDTO = new TokenRangeDTO();
int count = 0;
String header = "";
String next;
String line = bufferedReader.readLine();
LinkedHashSet<String> tokenRanges = new LinkedHashSet<>();
int trCount = 0;
boolean first = true;
boolean last = line == null;
while (!last) {
last = (next = bufferedReader.readLine()) == null;
if (!first && !last) {
tokenRanges.add(line);
}
// read first line of the file
else if (first && line.startsWith(H)) {
header = line;
first = false;
} else if (first && !line.startsWith(H)) {
tokenRangeDTO.setValidationMessage(HEADER_MISSING);
first = false;
}
// read last line of the file
else if (last && line.startsWith(T)) {
trCount = getTrailerCount(tokenRangeDTO, line, trCount);
} else if (last && !line.startsWith(T)) {
tokenRangeDTO.setValidationMessage(TRAILOR_MISSING);
}
line = next;
count++;
}
processInputFile(fileName, tokenRangeDTO, count, header, tokenRanges, trCount);
} catch (IOException e) {
LOGGER.error(IO_EXCEPTION, e);
} catch (Exception e) {
LOGGER.error("Some exception has occured", e);
} finally {
try {
FileUtils.deleteQuietly(new File(intransitDir + fileName));
} catch (Exception ex) {
LOGGER.error(STREAM_FAILURE, ex);
}
}
}
can anyone help me to reduce cylomatic complexity for below method upto 10..also considering no nesting of if else is allow as it will also cause sonar issue.
It will be great help for me
You could extract part of your code to methods and/or refactor some variables which could be used in other way. Also, when you have comments explaining your code it is a strong indicator that your logic can be improved there:
private void processIntransitFile(String fileName) {
if (StringUtils.isNotBlank(fileName)) return;
processFromIntransitDirectory(fileName);
}
private void processFromIntransitDirectory(String fileName) {
try (BufferedReader bufferedReader = new BufferedReader(getFileFromIntransitFolder(fileName))) {
TokenRangeDTO tokenRangeDTO = new TokenRangeDTO();
int count = 0;
String header = "";
String next;
String line = bufferedReader.readLine();
LinkedHashSet<String> tokenRanges = new LinkedHashSet<>();
int trCount = 0;
while (!isLastLine(line)) {
next = bufferedReader.readLine();
if (!isFirstLine(count) && !isLastLine(next)) {
tokenRanges.add(line);
}
header = readFirstLine(line, count, tokenRangeDTO);
trCount = readLastLine(line, next, trCount, tokenRangeDTO);
line = next;
count++;
}
processInputFile(fileName, tokenRangeDTO, count, header, tokenRanges, trCount);
} catch (IOException e) {
LOGGER.error(IO_EXCEPTION, e);
} catch (Exception e) {
LOGGER.error("Some exception has occured", e);
} finally {
try {
FileUtils.deleteQuietly(new File(intransitDir + fileName));
} catch (Exception ex) {
LOGGER.error(STREAM_FAILURE, ex);
}
}
}
private boolean isLastLine(String line) {
return line != null;
}
private String readFirstLine(String line, int count, TokenRangeDTO tokenRangeDTO) {
if (isFirstLine(count) && isHeader(line)) {
return line;
} else if (isFirstLine(count) && !isHeader(line)) {
tokenRangeDTO.setValidationMessage(HEADER_MISSING);
}
return StringUtils.EMPTY;
}
private int readLastLine(String line, String next, int trCount, TokenRangeDTO tokenRangeDTO){
if (isLastLine(next) && isTrailor(line)) {
return getTrailerCount(tokenRangeDTO, line, trCount);
} else if (last && !isTrailor(line)) {
tokenRangeDTO.setValidationMessage(TRAILOR_MISSING);
}
return 0;
}
private boolean isTrailor(String line) {
return line.startsWith(T);
}
private boolean isHeader(String line) {
return line.startsWith(H);
}
private boolean isFirstLine(int count) {
return count == 0;
}
private FileReader getFileFromIntransitFolder(String fileName) {
return new FileReader(intransitDir + fileName);
}
Doing this your code will be more readable, you will avoid useless variables using logic and your cyclomatic complexity will decrease.
For more tips, I recommend access refactoring.guru.

Processing huge File quickly in Java

I have a huge CSV file ~800 K records and using that data I have to form a POST request and make a rest call.
Initially I tried WITHOUT using threads but it is taking very long time to process it.
So I thought of using threads to speed up the process and followed below approach.
divided file into relatively smaller files (Tried with 3 files with approx ~5K data each file). (I Did this Manually Before passing to application)
Created 3 threads (traditional way by extending Thread class)
Reads each file with each thread and form HashMap with details required to form request and added it to ArrayList of POST Request
Send Post request to in loop
List item
Get the Response and add it to Response List
Both above approach takes too long to even complete half (>3 hrs). Might be one of them would not be good approach.
Could anyone please provide suggestion which helps me speeding up the process ? It is NOT mandatory to use threading.
Just to add that my code is at the consumer end and does not have much control on producer end.
MultiThreadedFileRead (Main class that Extends Thread)
class MultiThreadedFileRead extends Thread
{
public static final String EMPTY = "";
public static Logger logger = Logger.getLogger(MultiThreadedFileRead.class);
BufferedReader bReader = null;
String filename = null;
int Request_Num = 0;
HashMap<Integer, String> filteredSrcDataMap = null;
List<BrandRQ> brandRQList = null;
List<BrandRS> brandRSList = null;
ReadDLShipFile readDLShipFile = new ReadDLShipFile();
GenerateAndProcessPostBrandAPI generateAndProcessPostBrandAPI = new GenerateAndProcessPostBrandAPI();
MultiThreadedFileRead()
{
}
MultiThreadedFileRead(String fname) throws Exception
{
filename = fname;
Request_Num = 0;
List<BrandRQ> brandRQList = new ArrayList<BrandRQ>();
List<BrandRS> brandRSList = new ArrayList<BrandRS>();
this.start();
}
public void run()
{
logger.debug("File *** : " + this.filename);
//Generate Source Data Map
HashMap<Integer, String> filteredSrcDataMap = (HashMap<Integer, String>) readDLShipFile.readSourceFileData(this.filename);
generateAndProcessPostBrandAPI.generateAndProcessPostRequest(filteredSrcDataMap, this);
}
public static void main(String args[]) throws Exception
{
String environment = ""; // TO BE UNCOMMENTED
String outPutfileName = ""; // TO BE UNCOMMENTED
BrandRetrivalProperties brProps = BrandRetrivalProperties.getInstance();
if(args != null && args.length == 2 && DLPremiumUtil.isNotEmpty(args[0]) && DLPremiumUtil.isNotEmpty(args[1])) // TO BE UNCOMMENTED
{
environment = args[0].trim();
outPutfileName = args[1].trim();
ApplicationInitializer applicationInitializer = new ApplicationInitializer(environment);
applicationInitializer.initializeParams();
logger.debug("Environment : " + environment);
logger.debug("Filename : " + outPutfileName);
// TO BE UNCOMMENTED - START
}else{
System.out.println("Invalid parameters passed. Expected paramenters: Environment");
System.out.println("Sample Request: java -jar BrandRetrival.jar [prd|int] brand.dat");
System.exit(1);
}
MultiThreadedFileRead multiThreadedFileRead = new MultiThreadedFileRead();
List<String> listOfFileNames = multiThreadedFileRead.getFileNames(brProps);
logger.debug("List : " + listOfFileNames);
int totalFileSize = listOfFileNames.size();
logger.debug("totalFileSize : " + totalFileSize);
MultiThreadedFileRead fr[]=new MultiThreadedFileRead[totalFileSize];
logger.debug("Size of Array : " + fr.length);
for(int i = 0; i < totalFileSize; i++)
{
logger.debug("\nFile Getting Added to Array : " + brProps.getCountFilePath()+listOfFileNames.get(i));
fr[i]=new MultiThreadedFileRead(brProps.getCountFilePath()+listOfFileNames.get(i));
}
}
public List<String> getFileNames(BrandRetrivalProperties brProps)
{
MultiThreadedFileRead multiThreadedFileRead1 = new MultiThreadedFileRead();
BufferedReader br = null;
String line = "";
String filename = multiThreadedFileRead1.getCounterFileName(brProps.getCountFilePath(), brProps.getCountFilePathStartsWith());
List<String> fileNameList = null;
logger.debug("filename : " + filename);
if(filename != null)
{
fileNameList = new ArrayList<String>();
try{
br = new BufferedReader(new FileReader(brProps.getCountFilePath()+filename));
while ((line = br.readLine()) != null)
{
fileNameList.add(line);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block ;
e2.printStackTrace();
} catch (Exception e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e4)
{
e4.printStackTrace();
} catch (Exception e5)
{
e5.printStackTrace();
}
}
}
}
return fileNameList;
}
// Get the Name of the file which has name of individual CSV files to read to form the request
public String getCounterFileName(String sourceFilePath, String sourceFileNameStartsWith)
{
String fileName = null;
if(sourceFilePath != null && !sourceFilePath.equals(EMPTY) &&
sourceFileNameStartsWith != null && !sourceFileNameStartsWith.equals(EMPTY))
{
File filePath = new File(sourceFilePath);
File[] listOfFiles = filePath.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].getName().startsWith(sourceFileNameStartsWith)) {
fileName = listOfFiles[i].getName();
} else if (listOfFiles[i].isDirectory()) {
fileName = null;
}
}
}
return fileName;
}
}
GenerateAndProcessPostBrandAPI
public class GenerateAndProcessPostBrandAPI {
public static Logger logger = Logger.getLogger(GenerateAndProcessPostBrandAPI.class);
List<BrandRQ> brandRQList = new ArrayList<BrandRQ>();
List<BrandRS> brandRSList = new ArrayList<BrandRS>();
DLPremiumClientPost dlPremiumclientPost = new DLPremiumClientPost();
JSONRequestGenerator jsonRequestGenerator = new JSONRequestGenerator();
public List<BrandRQ> getBrandRequstList(Map<Integer, String> filteredSrcDataMap)
{
if(filteredSrcDataMap != null)
{
brandRQList = jsonRequestGenerator.getBrandRQList(filteredSrcDataMap, brandRQList);
}
return brandRQList;
}
public void generateAndProcessPostRequest(Map<Integer, String> filteredSrcDataMap, MultiThreadedFileRead multiThreadedFileRead)
{
if(filteredSrcDataMap != null)
{
brandRQList = jsonRequestGenerator.getBrandRQList(filteredSrcDataMap, brandRQList);
if(brandRQList != null && brandRQList.size() > 0)
{
BrandRetrivalProperties brProps = BrandRetrivalProperties.getInstance();
String postBrandsEndpoint = brProps.getPostBrandsEndPoint();
for (BrandRQ brandRQ : brandRQList)
{
multiThreadedFileRead.Request_Num = multiThreadedFileRead.Request_Num + 1;
logger.debug("Brand Request - " + multiThreadedFileRead.Request_Num + " : " + ObjectToJSONCovertor.converToJSON(brandRQ));
BrandRS brandResponse = dlPremiumclientPost.loadBrandApiResponseJSON(brandRQ, postBrandsEndpoint, DLPremiumUtil.getTransactionID(), BrandConstants.AUTH_TOKEN);
logger.debug("Response - " + multiThreadedFileRead.Request_Num + " : " + ObjectToJSONCovertor.converToJSON(brandResponse));
brandRSList.add(brandResponse);
}
}
}
}
}

parse CSV using BaneUtilBean

I am trying to parse a csv and map the fields to a POJO class. However I can see that the mapping is not achieved correctly.
I am trying to map the header from a POJO file to the csv.
public class CarCSVFileInputBean {
private long Id;
private String shortName;
private String Name;
private String Type;
private String Environment;
//getter and setters
}
Can someone please take a look at my code:
public class carCSVUtil {
private static Log log = LogFactory.getLog(carCSVUtil.class);
private static final List<String> fileHeaderFields = new ArrayList<String>();
private static final String UTF8CHARSET = "UTF-8";
static {
for (Field f : carCSVFileInputBean.class.getDeclaredFields()) {
fileHeaderFields.add(f.getName());
}
}
public static List<carCSVFileInputBean> getCSVInputList(InputStream inputStream) {
CSVReader reader = null;
List<carCSVFileInputBean> csvList = null;
carCSVFileInputBean inputRecord = null;
String[] header = null;
String[] row = null;
try {
reader = new CSVReader(new InputStreamReader(inputStream, UTF8CHARSET));
csvList = new ArrayList<carCSVFileInputBean>();
header = reader.readNext();
boolean isEmptyLine = true;
while ((row = reader.readNext()) != null) {
isEmptyLine = true;
if (!(row.length == 1 && StringUtils.isBlank(row[0]))) { // not an empty line, not even containing ','
inputRecord = new carCSVFileInputBean();
isEmptyLine = populateFields(inputRecord, header, row);
if (!isEmptyLine)
csvList.add(inputRecord);
}
}
} catch (IOException e) {
log.debug("IOException while accessing carCSVFileInputBean: " + e);
return null;
} catch (IllegalAccessException e) {
log.debug("IllegalAccessException while accessing carCSVFileInputBean: " + e);
return null;
} catch (InvocationTargetException e) {
log.debug("InvocationTargetException while copying carCSVFileInputBean properties: " + e);
return null;
} catch (Exception e) {
log.debug("Exception while parsing CSV file: " + e);
return null;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ioe) {}
}
return csvList;
}
protected static boolean populateFields(carCSVFileInputBean inputRecord, String[] header, String[] row) throws IllegalAccessException, InvocationTargetException {
boolean isEmptyLine = true;
for (int i = 0; i < row.length; i++) {
String val = row[i];
if (!StringUtils.isBlank(val)) {
BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val);
isEmptyLine = false;
}
}
return isEmptyLine;
}
}
I found the solution - the headers in the csv file are expected to begin with a lowercase.

ObjectInputStream wont load Array of Objects after second Run - Java

I've been trying to apply the followed code in a wider scheme. Right now I am just trying to understand the concept of ObjectInput/outputStreams and how they handle Array of objects.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class WritFile {
private FileInputStream output;
private ObjectInputStream outPut;
private FileOutputStream input;
private ObjectOutputStream inPut;
private Haha obj[];
public static void main(String args[]) throws Exception {
WritFile obj = new WritFile();
obj.Shazam("src\\Aloha.txt");
}
public void Shazam(String path) {
obj = new Haha[30];
for (int i = 0; i < obj.length; i++) {
obj[i] = new Haha();
}
for (int i = 0; i < 5; i++) {
obj[i].q1 = " Name" + i;
obj[i].x = i;
}
int No = 5;
saveToFile(obj, path);
int counter = 0;
try {
for (int i = 0; i < ReadFromFile(path).length; i++) {
if (ReadFromFile(path)[i].q1 != null) {
counter++;
}
}
for (int i = 0; i < counter; i++) {
if (ReadFromFile(path)[i] != null) {
obj[No++].q1 = ReadFromFile(path)[i].q1;
}
}
} catch (Exception e) {
System.out.printf("error1 : %s", e.getMessage());
e.printStackTrace();
}
try {
for (int i = 0; i < ReadFromFile(path).length; i++) {
if (ReadFromFile(path)[i] != null) {
System.out.println(ReadFromFile(path)[i].q1);
}
}
} catch (Exception e) {
System.out.printf("error2 : %s", e.getMessage());
}
System.out.printf("%s %n", "*******************");
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i].q1);
}
saveToFile(obj, path);
}
public void saveToFile(Haha arr[], String path) {
try {
input = new FileOutputStream(path, true);
inPut = new ObjectOutputStream(input);
inPut.writeObject(arr);
inPut.close();
} catch (Exception e) {
System.out.printf("Crashd : %s", e.getMessage());
}
}
public Haha[] ReadFromFile(String path) throws Exception {
output = new FileInputStream(path);
outPut = new ObjectInputStream(output);
return ((Haha[]) outPut.readObject());
}
}
My goal with this code is to store some data into an array of objects (OBJ) then save that array to a file using the function I created. Then read the data from the file and store it in the First empty index in the same array and so on.
For some reason it doesn't seem to write the data to the file after the first run :( !
Help!
public class SerializableArray implements Serializable, AutoCloseable{
/**
*
*/
private static final long serialVersionUID = 1L;
private static File ardatei;
transient Integer[] currentarray;
private int cntoverwrite;
FileInputStream fi;
BufferedReader br;
ObjectInputStream in;
int cnt;
public SerializableArray(Integer[] integers, String filename) throws IOException {
ardatei = new File(filename);
currentarray = integers;
if (!ardatei.exists())
{
try {
ardatei.createNewFile();
System.out.println("your file is created....");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("could not create File");
System.exit(-1);
}
FileOutputStream fos = new FileOutputStream(ardatei);
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(integers);
o.flush();
o.close();
} else if (ardatei.exists() || zustand > 0) {
FileOutputStream fos =
new FileOutputStream(ardatei);
ObjectOutputStream o =
new ObjectOutputStream(fos);
o.writeObject(integers);
o.writeObject("\n " + "your file was overwrite.");
System.out.println("your file exists and become overwritten");
o.flush();
o.close();
}
}
method to read data from given file
public SerializableArray(String filename) {
File f = new File (filename);
fi = null;
br= null;
in = null;
if (f.exists()){
try {
try {
fi = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
throw new FileNotFoundException("Loading file failed...");
}
in = new ObjectInputStream(fi);
System.out.println("Read data....");
//Cast to integer because readObject returns a object
currentarray =(Integer[]) in.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("could not read file....);
}
} else {
throw new RuntimeException ("this file doesnt exist yet");
}
}
that code works in my case ^^

Categories