Setting value of an attribute when uploading file to database - java

I have a .csv file "Salesman" that will be uploaded to the sqlite database. This file contains details about a Salesman.
A sample row for Salesman:
-----------
|code|name|
-----------
|0001|Jon|
-----------
|0002|Stu|
DDL for Salesman:
CREATE TABLE salesman (
code INTEGER NOT NULL,
name TEXT NOT NULL,
isSelected INTEGER NOT NULL,
PRIMARY KEY (
code
)
);
The attribute isSelected acts as a tag stating that the Salesman has been selected, thus cannot be chosen again.
This is my code for getting Salesman details from .CSV file:
public static ArrayList<Salesman> getSalesmanFromFile(String filePath){
ArrayList<Salesman> salesmanList= new ArrayList<Salesman>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
try {
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1]));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
String status = "Error"; //- Please review file selected. Make sure that format is followed.";
}
return salesmanList;
}
My question is, how can I set the third attribute isSelected in the method to 0 (not selected)? Since .csv file doesn't contain the tagging attribute, I'm thinking of placing it in the method above (which will be used at the start of the whole program).
I'm thinking of creating a variable within the method int isSelected = 0 but I don't know how to incorporate it with the BufferedReader. Something like:
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line = null;
String[] strSalesman = null;
//int isSelected = 0;
try {
while ((line=br.readLine()) != null){
strSalesman = line.split(",");
salesmanList.add(new Salesman(Integer.parseInt(strSalesman[0]), strSalesman[1], isSelected?));
}
} catch (IOException ex) {
ex.printStackTrace();
}
Any help would be appreciated!

Related

How to write a binary file from a String and retrieve it again to a String?

I have a string and want to persist it into a file and be able to retrieve it again into a String.
Something is wrong with my code because It's supposing that I must write something binary non readable but when i Open the file I can read this:
Original string:
[{"name":"asdasd","etName":"111","members":[]}]
Stored string in binary file:
[ { " n a m e " : " a s d a s d " , " e t N a m e " : " 1 1 1 " , " m e m b e r s " : [ ] } ]
I detect two problems:
Is not stored in binary! I can read it. It's supposed to be a confused binary text unreadable but I can read it.
When i retrieve it it's being retrieved with that strange space between the characters. So it doesn't works.
This is my code for storing the string:
public static void storeStringInBinary(String string, String path) {
DataOutputStream os = null;
try {
os = new DataOutputStream(new FileOutputStream(path));
os.writeChars(string);
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And this is my code for reading it from binary to a String:
public static String retrieveStringFromBinary(String file) {
String string = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e){
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string;
}
Firstly, there isn't really a distinction between a text file and a binary file. A text file is just a file who's content falls in the range of byte values that correspond to characters.
If you want to encrypt the content of the file so it is unreadable just by catting the file then you will need to choose an appropriate encryption method.
Secondly Mixing Readers/Writers and Streams in Java is never a good idea, pick one style and stick to it.
The problem with your function that saves the string to a file is that you are using the writeChars() method, which from the doc does the following:
Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.
Since your string is made up of single byte characters this is leading to the padding of your string with null bytes, which are being converted to spaces when read back in. If you change this to writeBytes() then you should get output without the extra null byte.
The null byte will also stop your read function working as the readLine() function will return null on it's first call due to the leading 0x00 in the file.
Try this out:
public static void storeStringInBinary(String string, String path) {
try(ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(path))) {
os.writeObject(string);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String retrieveStringFromBinary(String file) {
String string = null;
try (ObjectInputStream reader = new ObjectInputStream(new FileInputStream(file))){
string = (String) reader.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return string;
}

Importing CSV into MySQL through JAVA

So I'm trying to import a CSV file into my MySQL database through my Java program. The program imports everything that's in the file, like it's suppose to, but the first row, it send to the end of the table, and the program see it's there, but if I search for that nr, it says it doesn't exists. And if I go directly to the database table and edit the nr(if the nr is 137, and I edit and write 137 again) the program recognize that nr, and if I search for it, it will find, and the database table organizes itself and sends that entry where is suppose to be.
I just don't see any logic in this. I someone could help me out, I'd appreciated.
LOAD DATA INFILE 'C:\\Users\\carla.DESKTOP-9364K9K\\Desktop\\Alunos_1.csv'
INTO TABLE utentes character set utf8
FIELDS TERMINATED BY ','
(NrProcesso, Nome, #Nome_Resumido, Ano, Turma, #Subsidio, #Nome_EE, #NIF, #email, #Obs)
SET
Subsidio = IF(#Subsidio='','Nenhum',#Subsidio),
Nome_Resumido = IF(#Nome_Resumido='',NULL,#Nome_Resumido),
Nome_EE = IF(#Nome_EE='',NULL,#Nome_EE),
NIF = IF(#NIF = '', NULL,#NIF),
email = IF(#email='',NULL,#email),
Obs = IF(#Obs='',NULL,#Obs);
Thanks in advance.
You have do do something to check cell/column value and form a sql to inject in MySQL.
public List<Object> getRecordingsListFromCsv(String csvFileLocation, String mp3FileLocation, String mp3FileLocation2, String saveFileLocation, ChannelSftp sftp) {
Map<String, File> recordingsFilesMap = null;
BufferedReader br = null;
List<String> errorFilesList = new ArrayList<>();
List<Object> tempList = new LinkedList<>();
try {
csvRows = 0;
recordingsFilesMap = new LinkedHashMap<>();
br = new BufferedReader(new FileReader(csvFileLocation));
String line = br.readLine();
scriptLog.info("\n" + csvFileLocation + " loaded. Parsing File...");
while ((line = br.readLine()) != null) {
String[] csvArray = parseCsvLineToArray(line);
// System.out.println(Arrays.asList(csvArray) + "\n\n");
if (csvArray[0].trim().isEmpty()) {
continue;
}
/* Do your stuff here */
csvRows++;
}
} catch (FileNotFoundException e) {
scriptLog.error("\n---ERROR---\n FILE NOT FOUND: " + csvFileLocation);
String errorStr = "Type=" + e.toString();
errorStr += "StackTrace=" + Arrays.toString(e.getStackTrace());
scriptLog.error(errorStr);
} catch (IOException e) {
String errorStr = "Type=" + e.toString();
errorStr += "StackTrace=" + Arrays.toString(e.getStackTrace());
scriptLog.error(errorStr);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
Hope it will help you at some extent!!

Java-Write in file

I want get name, last name and a spacial code from user, and save in one array, after that write to a file. My code doesn't have compiler error but it doesn't work.
public class WriteFile {
public static void main(String[] args){
try {
String array[][] = new String[100][2];
for (int i = 0; i < array.length; i++) {
RandomAccessFile raf=new RandomAccessFile("D://employee.txt","rw");
String inputName=JOptionPane.showInputDialog("Please Insert First Name");
array[i][0]=inputName;
String inputLName=JOptionPane.showInputDialog("Please Insert Last Name");
array[i][1]=inputLName;
String inputMeliiC=JOptionPane.showInputDialog("Please Insert Melii Code");
array[i][2]=inputMeliiC;
raf.writeUTF(array[i][0]);
raf.writeUTF(array[i][1]) ;
raf.writeUTF(array[i][1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
You are doing many things wrong.
First of all, why do you use an array at all here? It is unwarranted. Collect in a List!
Second: .writeUTF() will not write text.
Third: why write as you ask for input? Write all at once.
Fourth: you don't close your resource at all.
Ask for input first, then attempt to write to the file. And don't use File, it's obsolete. Use this (supposes Java 7+):
final Path dst = Paths.get("d:\\employee.txt");
// Change open options if necessary
try (
final BufferedWriter writer = Files.newBufferedWriter(dst,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
) {
// write your data
}
Or even better yet, use this. Provided you have collected all of your employee data in a List as I suggest, and not an array, this is as easy as:
Files.write(thePath, myList, StandardCharsets.UTF_8, yourOpenOptionsHere);
Ok well you can for this modified code:
public static void main(String[] args){
RandomAccessFile raf = null;
try {
String array[][] = new String[2][3];
raf=new RandomAccessFile("D:\\employee.txt","rw");
for (int i = 0; i < array.length; i++) {
String inputName=JOptionPane.showInputDialog("Please Insert First Name");
array[i][0]=inputName;
String inputLName=JOptionPane.showInputDialog("Please Insert Last Name");
array[i][1]=inputLName;
String inputMeliiC=JOptionPane.showInputDialog("Please Insert Melii Code");
array[i][2]=inputMeliiC;
raf.writeChars(array[i][0]);
raf.writeChar(':');
raf.writeChars(array[i][1]) ;
raf.writeChar(':');
raf.writeChars(array[i][2]);
raf.writeChars("\n");
}
raf.seek(0);
String str = raf.readLine();
while(str != null ){
System.out.println(str);
String arr[] = str.split(":");
System.out.println(Arrays.asList(arr));
str = raf.readLine();
}
raf.close();
} catch (FileNotFoundException e) {
try {
raf.close();
} catch (IOException ex) {
Logger.getLogger(Ideone.class.getName()).log(Level.SEVERE, null, ex);
}
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
try {
raf.close();
} catch (IOException ex) {
Logger.getLogger(Ideone.class.getName()).log(Level.SEVERE, null, ex);
}
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
Couple of issues:
You defined array as new String[100][2] and using it till the index array[i][2]=inputMeliiC; As array starts from 0, you should define your array as new String[100][3]. Are you doing further processing on your array?
You are not writing the inputMeliiC, instead you are duplicating the inputLName bu doing raf.writeUTF(array[i][1]); twice. You should do raf.writeUTF(array[i][2]);
Most importantly why you r write is not working is, you need to flush out the buffer. So you should do raf.close(); once you are done. Make sure UTF wont write in simple text as you are entering and you are opening file in both read write mode.

Java Program keeps inserting the same line into my file

so I am trying to read a file and add two lines of code to it at the top. So far that hadn't been working so I tried just reading the lines and writing them back. This was a major failure. It only writes to one of the files in the directory and just keeps filling it with the xmlopentag even though its been commented out, over and over. If anyone has any ideas it would be appreciated.
ArrayList<String> lines = new ArrayList();
BufferedReader reader = null;
String xmlstylesheet = "<?xml-stylesheet type=\"text/xsl\" href=\""+stylefilename+"\"?>";
String xmlopentag = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
for(int i=0;i<files.length;i++) {
lines.clear();
try {
reader = new BufferedReader(new FileReader(files[i]));
String text = null;
while ((text = reader.readLine()) != null) {
lines.add(text);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
//lines.add(1, xmlstylesheet);
//lines.add(0, xmlopentag);
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(files[i])));
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(i));
}
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
writer.write(lines.get(i));
should probably be
writer.write(lines.get(j));
for loop for PrintWriter operation is having an index j for iteration but using i to get the list value
please check it properly and change below code
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(i));
}
to
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(j));
}

filtering files

I want to check the file-type of a file. I thought about magic numbers, but how to use it
with Java.
I want only allow Textfiles and filter files like jpg etc. in my programm.
Some ideas, what can I do.
private String path;
private String fileText;
private String textLine;
public LoadModel(String path) {
this.path = path;
this.fileText = "";
FileReader read = null;
BufferedReader bufRead = null;
if (path != null && new File(path).exists()
&& !(new File(path).isDirectory())) {
try {
read = new FileReader(path);
bufRead = new BufferedReader(read);
do {
try {
this.textLine = bufRead.readLine();
} catch (IOException ex) {
Logger.getLogger(LoadModel.class.getName()).log(Level.SEVERE, null, ex);
}
if (this.textLine != null) {
this.fileText = this.fileText + this.textLine + "\n";
}
} while (this.textLine != null);
} catch (FileNotFoundException ex) {
Logger.getLogger(LoadModel.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
HinweisDialogController.hinweisDialogOK("Die angegebene Datei existiert nicht");
}
}
Here you can find the list of API's available for identify mime type in java with code sample.
Also in java 7 have an option
Files.probeContentType(path)
.
You can try java.nio.file.Files.probeContentType which is designed to determine a file content type. For example this test
System.out.println(Files.probeContentType(Paths.get("1.xml")));
System.out.println(Files.probeContentType(Paths.get("1.txt")));
prints
text/xml
text/plain
see API for more details
If you need your code to work on earlier versions of JDK (not JDK7) you may use Apache Tika's MimeType detector, which has MimeType#detect() method
More information here

Categories

Resources