I've been trying for days to learn how to create this code. It's a homework example. Beginner Java Final Project. I'm about to rip out my hair, if you could guide me a little, I'd appreciate it. I can't seem to figure out how to parse the csv file into a proper 2d array. The delimiter is a ",". I need to maniuplate one column of data (such as the year), but ignore the first (0,0), (0,1), (0,2) row as it only carries the labels I believe. I'm so lost. What I have prints out the first column, but how would I ignore the label at (0,0), and how would I store this information so I could manipulate it in a method? I don't need help on most of the assignment except how to read the values properly and then be able to manipulate them. Thank you.
import java.util.*;
import java.io.*;
public class BasicFileIO{
public static void main (String[] args) {
String fileName = "Crime.csv";
File file = new File(fileName);
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String data = input.nextLine();
String[] values = data.split(",");
System.out.println(values[0]);
}
}catch (Exception e) {
System.out.printf("Error");
}
}
}
HERE IS AN IMAGE OF THE CSV FILE. I couldn't upload it. This is how it looks in google docs, but if I open it in atom it's just a file with commas and values (not in cells).
CSV screenshot
You can read and parse scv files with apache commons-csv. Here's an example for reading the columns with this library:
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name"); // or you can pass the index of column
String firstName = record.get("First Name");
}
Related
I am trying to print 2 different arrays, One array has the name of the file and the other array has the content of the csv file.
First I am reading the contents of the given file through the path and then putting the content of the .csv file into an array which is nextLine[]
public static void fileRead(File file) throws IOException, CsvException {
CSVReader csvReader = new CSVReaderBuilder(new FileReader(file)).withSkipLines(1).build();
String[] nextLine;
File folder = new File("src/main/resources/FolderDocumentsToRead");
String[] fileList = folder.list();
while((nextLine = csvReader.readNext())!=null){
System.out.println("Name of file: "+fileList[0]+", Title of Text: "+nextLine[0]);
}
}
}
The output I am trying to get is meant to look like;
Name of file: ATale.csv, Title of Text: A TALE OF THE RAGGED MOUNTAINS
Name of file: Diggling.csv, Title of Text: DIDDLING
The output I am getting looks like;
Name of file: ATale.csv, Title of Text: A TALE OF THE RAGGED MOUNTAINS
Name of file: ATale.csv, Title of Text: DIDDLING
I have tried using loops to get to the correct solution but I was just getting errors thrown at me and having a hard time with them.
I'm fairly new to using arrays and java in general, any tips would be appreciated even a tip towards getting the solution.
P.S first time using Stack overflow ahaha
Before the while loop, if you create a variable to keep track of the selected index then you will be able to modify it and have the change stay after the loop has finished.
int index = 0;
while(csvReader.hasNext())
{
String fileName = fileList[index];
String title = nextLine[index];
index++;
...
}
The line
while((nextLine = csvReader.readNext())!=null)
can be/should be rewritten like so:
while(csvReader.hasNext())
{
nextLine = csvReader.readNext();
...
}
This helps a lot with reading/debugging
NOTE this is not any sort of solution but a recommendation for ease-of-use
Apologies in advance for any formatting/other errors, I am still very much a newbie to Java.
I am conducting a gene expression analysis in which I have a program that prints ~ 6 million gene names and their expression values in 23,000 sets of 249 (there are 249 patients total and they each have 23,000 genes/gene expression values). Right now, I have this program looping through all the 249 individual patient files, obtaining the 23,000 gene values, and printing to a text file (with 6 million rows and 2 columns, one column for gene name and one for expression).
However, I would like this program to print to an excel file instead, so that there are 249 rows (for each patient) and 23,000 columns (for each gene). I have been trying for a couple of days to do this (with apache POI) and still am unable to. I found this example code: https://www.scientecheasy.com/2019/01/write-excel-file-in-java.html, which is what I have been trying to modify to fit my program, but nothing seems to be working. I have included my original program (that prints to the text file but also include the POI jars I downloaded). Any help would be MUCH appreciated!
import java.io.*;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcel {
public static final File folder = new File("C:/Users/menon/OneDrive/Documents/R/TARGET");
private static PrintStream output;
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = wb.createSheet("values");
public static void main(String [] args) throws FileNotFoundException {
output = new PrintStream(new File("final_CSRSEF_data.txt"));
listFilesForFolder(folder);
}
public static double listFilesForFolder(final File folder) throws FileNotFoundException {
double value = 0.0;
//contains names of all the 23k genes in order to loop through the 249 files and collect the needed names each time
File list = new File("C:/Users/menon/OneDrive/Documents/NamesOfGenes.txt");
Scanner names = new Scanner(list);
String data;
while (names.hasNext()) {
String name = names.next();
//looping through all separate 249 patient files in folder and searching for gene name
for (final File fileEntry : folder.listFiles()) {
Scanner files = new Scanner(fileEntry);
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
while (files.hasNextLine()) {
final String lineFromFile = files.nextLine();
if(lineFromFile.contains(name)) {
//System.out.print(name+ " in file " + fileEntry.getName());
String[] thisOne = lineFromFile.split("\\s");
String res = thisOne[0];
//System.out.println(res);
if (res.equals(name)) {
print(lineFromFile);
print("\n");
}
}
}
}
}
print("----------------");
print("\n");
}
return 0.0;
}
//print to final_CSRSEF_data.txt
private static void print(String stat) {
output.print(stat);
}
}
So basically what I am printing before the "---------------" in each text file should instead be in a separate column (not row) in an excel sheet.
Once again, thank you in advance!
try look at this:
www.pela.it, in my home page there's a link to download "gene expression" tool
i did it in java two years ago and if it is what you are trying to do i'll be happy to help.
It elaborate an xml raw data output from pcr tool and finally print a paginated excel with all elaboration phases. There's a ppt too that explain in detail.
I have an arraylist that I want to verify with the rows of a csv file.
Everytime the arraylist has different elements as I am creating that arraylist dynamically and adding element text from my webpage. But I wanna access the csv data horizontally i.e. everytime I want to veryfy the row data with my arraylist. Please give me a solution for this.
You can try doing something like this:
try (BufferedReader br = new BufferedReader (new FileReader (path))){
Stream<String> lines = br.lines();
String[] linesArray = lines.toArray();
if (index < linesArray.length) {
String line = linesArray[index];
//then you can do your verification
}
}
I need to write a program for a project at university which should cut some specific parts out of a given CSV File. I've started already but I don't know how to keep only the content (sentence and vote values) or min. to remove the date part.
PARENT,"Lorem ipsum...","3","0","Town","09:17, 29/11/2016"
REPLY,"Loren ipsum...”,"2","0","Town","09:18, 29/11/2016"
After the program ran I want to have it like this:
Lorem ipsum... (String) 3 (int) 0 (int)
Loren ipsum... (String) 2 (int) 0 (int)
I have no problem with writing a parser (read in, remove separators) but I don't know how realize this thing.
You can create your own data structure that contains a string, and two integers and then do the following while reading from the csv file. Only include the stuff you want from the csv based on the column number which is the index of the String array returned by the split() method.
Scanner reader = new Scanner(new File("path to your CSV File"));
ArrayList<DataStructure> csvData = new ArrayList<>();
while(reader.hasNextLine())
{
String[] csvLine = reader.nextLine().split(",");
DataStructure data = new DataStructure(
csvLine[1],
Integer.parseInt(csvLine[2]),
Integer.parseInt(csvLine[3]));
csvData.add(data);
}
I'm working on a program that requires quick access to a CSV comma-delimited spreadsheet file.
So far I've been able to read from it easily using a BufferedReader.
However, now I want to be able to edit the data it reads, then export it BACK to the CSV.
The spreadsheet contains names, phone numbers, email addresses, etc. And the program lists everyone's data, and when you click on them it brings up a page with more detailed information, also pulled from the CSV. On that page you can edit the data, and I want to be able to click a "Save Changes" button, then export the data back to its appropriate line in the CSV--or delete the old one, and append the new.
I'm not very familiar with using a BufferedWriter, or whatever it is I should be using.
What I started to do is create a custom class called FileIO. It contains both a BufferedReader and a BufferedWriter. So far it has a method that returns bufferedReader.readLine(), called read(). Now I want a function called write(String line).
public static class FileIO {
BufferedReader read;
BufferedWriter write;
public FileIO (String file) throws MalformedURLException, IOException {
read = new BufferedReader(new InputStreamReader (getUrl(file).openStream()));
write = new BufferedWriter (new FileWriter (file));
}
public static URL getUrl (String file) throws IOException {
return //new URL (fileServer + file).openStream()));
FileIO.class.getResource(file);
}
public String read () throws IOException {
return read.readLine();
}
public void write (String line) {
String [] data = line.split("\\|");
String firstName = data[0];
// int lineNum = findLineThatStartsWith(firstName);
// write.writeLine(lineNum, line);
}
};
I'm hoping somebody has an idea as to how I can do this?
Rather than reinventing the wheel you could have a look at OpenCSV which supports reading and writing of CSV files. Here are examples of reading & writing
Please consider Apache commons csv.
To fast understand the api, there are four important classes:
CSVFormat
Specifies the format of a CSV file and parses input.
CSVParser
Parses CSV files according to the specified format.
CSVPrinter
Prints values in a CSV format.
CSVRecord
A CSV record parsed from a CSV file.
Code Example:
Unit test code:
The spreadsheet contains names, phone numbers, email addresses, etc. And the program lists everyone's data, and when you click on them it brings up a page with more detailed information, also pulled from the CSV. On that page you can edit the data, and I want to be able to click a "Save Changes" button, then export the data back to its appropriate line in the CSV--or delete the old one, and append the new.
The content of a file is a sequence of bytes. CSV is a text based file format, i.e. the sequence of byte is interpreted as a sequence of characters, where newlines are delimited by special newline characters.
Consequently, if the length of a line increases, the characters of all following lines need to be moved to make room for the new characters. Likewise, to delete a line you must move the later characters to fill the gap. That is, you can not update a line in a csv (at least not when changing its length) without rewriting all following lines in the file. For simplicity, I'd rewrite the entire file.
Since you already have code to write and read the CSV file, adapting it should be straightforward. But before you do that, it might be worth asking yourself if you're using the right tool for the job. If the goal is to keep a list of records, and edit individual records in a form, programs such as Microsoft Access or whatever the Open Office equivalent is called might be a more natural fit. If you UI needs go beyond what these programs provide, using a relational database to keep your data is probably a better fit (more efficient and flexible than a CSV).
Add Dependencies
implementation 'com.opencsv:opencsv:4.6'
Add Below Code in onCreate()
InputStreamReader is = null;
try {
String path= "storage/emulated/0/Android/media/in.bioenabletech.imageProcessing/MLkit/countries_image_crop.csv";
CSVReader reader = new CSVReader(new FileReader(path));
String[] nextLine;
int lineNumber = 0;
while ((nextLine = reader.readNext()) != null) {
lineNumber++;
//print CSV file according to your column 1 means first column, 2 means
second column
Log.e(TAG, "onCreate: "+nextLine[2] );
}
}
catch (Exception e)
{
Log.e(TAG, "onCreate: "+e );
}
I solved it using
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.8.6</version>
</dependency>
and
private static final CsvMapper mapper = new CsvMapper();
public static <T> List<T> readCsvFile(MultipartFile file, Class<T> clazz) throws IOException {
InputStream inputStream = file.getInputStream();
CsvSchema schema = mapper.schemaFor(clazz).withHeader().withColumnReordering(true);
ObjectReader reader = mapper.readerFor(clazz).with(schema);
return reader.<T>readValues(inputStream).readAll();
}