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
Related
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");
}
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 have a code that reads a file using buffered reader and split, said file was created via a method that automatically adds 4KB of empty space at the beginning of the file, this results in when I read the following happens:
First the Code:
BufferedReader metaRead = new BufferedReader(new FileReader(metaFile));
String metaLine = "";
String [] metaData = new String [100000];
while ((metaLine = metaRead.readLine()) != null){
metaData = metaLine.split(",");
for (int i = 0; i < metaData.length; i++){
System.out.println(metaData[i]);
}
}
This is the result, keep in mind this file already exists and contains the values:
//4096 spaces then the first actual word in the document which is --> testTable2
Name
java.lang.String
true
No Reference
Is there a way to skip the first 4096 spaces, and get straight to the actual value within the file so I can get the result regularly? Because I'll be using the metaData array later in other operations, and I'm pretty sure the spaces will mess up the number of slots within the array. Any suggestions would be appreciated.
If you're using Eclipse, the auto-completion should help.
metaRead.skip(4096);
https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html
You could (as mentioned) simply do:
metaRead.skip(4096);
If the whitespace always occupies that many characters, or you could just avoid lines which are empty
while ((metaLine = metaRead.readLine()) != null){
if(metaLine.trim().length() > 0){
metaData = metaLine.split(",");
for (int i = 0; i < metaData.length; i++){
System.out.println(metaData[i]);
}
}
}
Basically, I want to parse, line by line, a Text file so that every line is in it's own array value.
E.g.
Hi There,
My Name's Aiden,
Not Really.
Array[0] = "Hi There"
Array[1] = "My Name's Aiden"
Array[2] = "Not Really"
But all the examples I have read already just confuse me and lead me to get frustrated. Maybe it's the way I approach it.
I don't know how to go about it, a point in the right direction would be most satisfying.
My suggestion is to use List<String> instead of String[] as arrays have fixed size, and that size is unknown before reading. Afterward one could make an array out of it, but to no real purpose.
For reading one has to know the encoding of the file.
Path path = Paths.get("C:/Users/Me/list.txt");
//Charset encoding = StandardCharsets.UTF_8;
Charset encoding = Charset.defaultCharset();
List<String> lines = Files.readAllLines(path, encoding);
for (String line : lines) {
...
}
for (int i = 0; i < lines.size(); ++i) {
String line = lines.get(i);
lines.set(i, "-- " + line;
}
I have a class called Name like so.
public Name (String first, String last)
This is a text file that contains names, its filename is "names.txt".
John Doe
Jane Doe
The file called "names.txt" is read in like so.
File read = new File ("names.txt");
Scanner in = new Scanner(read);
I want to know how to automatically create a new name object using the first word (John) as the first parameter and the second word (Doe) as the second parameter.
How do I do this?
Ok, I'll help you out. The line you want is
Name n = new Name(in.next(), in.next());
It's that simple, although this is not a particularly robust way.
read the file using scanner and include the split portion
//while(scanner) iterate the scanner upto end of the file read every line
{
String[] splitResult = input.split(" ");
firstName = splitResult[0];
lastName = splitResult[1];
storeMethod(firstName,lastName); // use this method to store the first name and last name
}