Reading contents of excel file - java

I am looking for some help with reading contents from a excel file.
Here is the code, I want it to read from the .csv file and
generate the result for the same.
My error shows
java.lang.NumberFormatException: For input string: "companycode"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at java.lang.Double.valueOf(Double.java:502)
at testgbt.TestGBT.main(TestGBT.java:40)
Please help and thanks in advance!!
package testgbt;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Vector;
import java.io.FileOutputStream;
import testgbt.BoostingTree;
import testgbt.BoostingTree.ResultFunction;
public class TestGBT {
public static void main(String[] args) {
String data_name = "C:\\Mihir\\NetBeans\\TestGBT\\data.csv";
Vector<Vector<Double>> x = new Vector<Vector<Double>>();
Vector<Double> y = new Vector<Double>();
try {
FileInputStream fis = new FileInputStream("C:\\Mihir\\NetBeans\\TestGBT\\data.csv");
// -------- load data from the file -------------
// get object of data input stream
BufferedReader b_reader = new BufferedReader(new
InputStreamReader(new FileInputStream(data_name))); // buffer
String read_line;
while ((read_line = b_reader.readLine()) != null) {
String[] str_list = read_line.trim().split(",");
Vector<Double> buffer_x = new Vector<Double>();
buffer_x.add(Double.valueOf(str_list[0]));
x.add(buffer_x);
y.add(Double.valueOf(str_list[1]));
}
b_reader.close();
// --------- learn a function of y=f(x) -------
BoostingTree gbt_ranker = new BoostingTree();
ResultFunction res_fun = gbt_ranker.gradient_boosting_tree(x, y);
// --------- save the curve fitting result y=f(x) ------
FileWriter file_writer = new FileWriter("C:\\Mihir\\NetBeans\\TestGBT\\result.txt");
FileOutputStream fos=new FileOutputStream("C:\\Mihir\\NetBeans\\TestGBT\\result.csv");
for (int i = 0; i < x.size(); i ++) {
file_writer.append(String.format("%f,%f,%f\n",
x.get(i).get(0),
res_fun.get_value(x.get(i)),
y.get(i)));
}
file_writer.close();
} catch (Exception err) {
err.printStackTrace();
System.exit(0);
}
}
}

Does your input CSV have a header row? Remove the header row from your input data or change your code to skip the first line.
You can skip the first row easily by changing this line:
String read_line;
to this:
String read_line = b_reader.readLine();

Looks like str_list[1] isn't the data you're looking for. In fact, it looks like you're trying to convert one of your column headers into a double. You probably just need to skip past the headers.

Related

Importing csv in android application

I've found this code on a previously answered question to import a csv in an android application, i have to import into my android application a file called data.csv, i then need to perform searches on said database, the rows as such:
178464;AA1
...
here's the code:
package com.cdac.qrcodescanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List read(){
List resultList = new ArrayList();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(";");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
and here's what goes where i want to use my data:
InputStream inputStream = getResources().openRawResource(R.raw.data);
CSVFile csvFile = new CSVFile(inputStream);
List scoreList = csvFile.read();
i now want to use the get method to have the string after the semicolon (the value), and so i tried:
String i = scoreList.get(178464);
That prompts me with the error:
incompatible types:
Required: Java.lang.string
Found: Java.lang.Object
doing this fixed the error but made my application crash:
String i = (string)scoreList.get(178464);
Object i = scoreList.get(178464);
I'm not particularly expert with Java, but i have the feeling i'm doing something incredibly wrong and i can't for the life of me figure out what, any help would be appreciated!
In the CSVFile.read() method, we have the following :
String[] row = csvLine.split(";");
resultList.add(row);
The resultList will be a list of arrays of strings. Each element of the list is a row of your file. Each element of the array is a value (column).
So...
String i = (string)scoreList.get(178464);
returns the 178464th line of the file. I'm assuming it will crash because you do not have 178464 lines in your files, and even if you did, the value returned should be a String[].
I'm assuming you wish to index each element by it's id (178464 in your example) and access it using this id. You should use a Map instead.
Map resultMap = new HashMap();
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(";");
String id = row[0];
Integer score = Integer.parseInt(row[1]);
resultMap.put(id, score);
}
Then you can access the map using the ids :
Integer score = resultMap.get("178464");

File I/O Practice.

I'm trying to take names from a file called boysNames.txt . That contains 1000 boy names. for Example every line looks like this in the file looks like this:
Devan
Chris
Tom
The goal was just trying to read in the name, but I couldn't find a method in the java.util package that allowed me to grab just the name in the file boysName.txt .
For example I just wanted to grab Devan, then next Chris, and tom.
NOT "1. Devan" and "2. Chris."
The problem is hasNextLine grabs the whole line. I don't want the "1." part.
So I just want Devan, Chris, Tom to be read or stored in a variable of type String. Does anyone know how to do that? I've tried HasNext(), but that didn't work.
Here the code here so you can get a visual:
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.FileInputStream;
public class PracticeWithTxtFiles {
public static void main(String[] args){
PrintWriter outputStream = null;
Scanner inputStream = null;
try{
outputStream = new PrintWriter(new FileOutputStream("boys.txt")); //opens up the file boys.txt
inputStream = new Scanner(new FileInputStream("boyNames.txt"));//opens up the file boyNames.txt
}catch(FileNotFoundException e){
System.out.println("Problem opening/creating files");
System.exit(0);
}
String names = null;
int ssnumbers= 0;
while(inputStream.hasNextLine())//problem is right here need it to just
// grab String representation of String, not an int
{
names = inputStream.nextLine();
ssnumbers++;
outputStream.println(names + " " + ssnumbers);
}
inputStream.close();
outputStream.close();
}
}
If you are unaware, Check for this String API's Replace method
String - Library
Just do a replace, its as simple as that.
names = names.replace(".","").replaceAll("[0-9]+","").trim()

Java: Trouble writing primitive data to a file

I'm trying to write primitive data such Int, Float, Double to a file in Java. Whenever I run the program the text file contains some random characters. I am using jdk1.8.0_25 and Npp editor. Here's the sample code I've obtained
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Tad {
public static void main(String[] args) throws IOException {
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
new File("E:\\temp.txt"))));
for (int i = 0; i < 10; i++)
dos.writeInt(i);
dos.close();
}
}
The output is not pastable here but it has spaces and some weird symbols which are not a part of the keyboard layout.
You want to "write" contents to a file, you don't want to write its binary representation.
So you have to use "Writer" Implementation's in Java not "OutputStream"
You see strange symbols in your file, because they are the binary representation of your data (ASCII codes).
Following code achieves what you are looking for.
Happy learning!
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
class Test123 {
public static void main(String[] args) throws IOException {
Writer dos = new BufferedWriter(
new FileWriter(new File("C:\\temp.txt")));
for (int i = 0; i < 10; i++)
dos.write(String.valueOf(i));
dos.close();
}
}
That Random characters are the ASCII representation of the decimal 0, 1, 2, 3 and so on till 127, you can see the ASCII values in the following table where 0 = null, 1 = start of heading and so on.
Here is an example of what you want to achieve in my style.
public class Tad {
public static void main(String[] args) throws IOException {
FileWriter dos = new FileWriter(new File("E:\\temp.txt"));
for (int i = 0; i < 10; i++)
dos.write(i+"");
dos.close();
}
}
and the following is an example in your style with a little change, I have used dos.writeChars(Integer.toString(i)); instead of dos.writeInt(i);.
public class Tad {
public static void main(String[] args) throws IOException {
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(
new File("E:\\temp.txt"))));
for (int i = 0; i < 10; i++){
dos.writeChars(Integer.toString(i));
}
dos.close();
}
}
Try using FileWRiter. I don't have a compiler at hand, but it should be something like this:
import java.io.*
public static writeString(String text)
{
private static String fileName= "put path and file here";
try{
File file = new File(fileName);
FileWriter writer = new FileWriter(file, true); //true means append to the file instead of purging the file every entry.
writer.write(text);
writer.close(); //close the output
}catch(IOException e){
System.err.println("ioexception: " + e.getMessag());
}
}
I'll check the code when I'm home to see if there are no problem, provided nobody gives better answer until that time, but this should at least put you on the right track.
NOTE - you should handle exceptions in IO

Java: deleting text in an csv which starts with --

I am loading a csv file and kept alive without closing BufferReader. Now I want to delete all lines which starts with -- and save that csv in a temp CSV. Anybody have an idea how I can do this find only c# code.
I tried to fix with regular expression but I failed.
An example of the csv:
-- DDL- "T453453 "."BMG"
-- DDL- "T423342 "."BMG234"
CREATE TABLE "T453453 "."BMG"
-- DDL- "T42234234 "."BMG236"
So it works but i have the last problem how i can add \n (Newline) cause if i debug this code i get the text in one line.
import java.io.BufferedReader;
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.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CsV {
public static String Read() throws IOException{
return new String(Files.readAllBytes(Paths.get("C://Users//myd//Desktop//BW//BWFormated.csv")));
}
public static void main(String[] args) throws IOException {
File inputFile = new File("C://Users//myd//Desktop//BW//BWtest.csv");
File tempFile = new File("C://Users//myd//Desktop//BW//BWFormated.csv");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "--";
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(Read());
}
}
You can check each line, if it begins with -- using String.startsWith() method.
If so, read the next line and if the line has content you want to make other things with, you can put it into a list. Maybe like this:
String line;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null)
{
if(line.startsWith("--"))
continue;
list.add(line);
}
for(int i = 0; i < list.length; i++)
{
line = list.get(i);
// use regular expressions to extract the data you want to convert into CSV format
}
Hint: I didn't check my syntax, so it could be, that it won't be compiled ;-)
Use the Pattern class for regular expressions and maybe this tutorial will help you.
Good luck!
EDIT
Extend your while-loop to the following, which allows you to add new lines, too:
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove))
continue;
writer.write(currentLine);
writer.newLine(); // Writes a line separator.
}
Read the docs to the newLine() method.

Java Regex to remove all words after a key till end key

Can anyone out there please help me ,
i have a file containing several important information but also containing irrelevant information inside it as well . the irrelevant information is mentioned inside a curly
bracket for example :
Function blah blah 1+2 {unwanted information} something+2
what i wish to do is remove the unwanted information, and display the out put like this :
Function blah blah 1+2 something+2
can some 1 please give me the regex code for this ?
I have a partial code for this
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
public class SimpleReader{
public static void main( String a[] )
{
String source = readFile("source.java");
}
static String readFile(String fileName) {
File file = new File(fileName);
char[] buffer = null;
try {
BufferedReader bufferedReader = new BufferedReader( new FileReader(file));
buffer = new char[(int)file.length()];
int i = 0;
int c = bufferedReader.read();
while (c != -1) {
buffer[i++] = (char)c;
c = bufferedReader.read();
}
} catch (IOException e) {
e.printStackTrace();
}
return new String(buffer);
}
}
Thanks in advance.
newstr = str.replaceAll("{[^}]*}", "");
Modified the answer from this question: How to remove entire substring from '<' to '>' in Java

Categories