Get filename while reading csv - java

I want to read values from csv files, and order them in a table (console output).
How can I output all files in a folder and read all content in this files, and get filename while reading files with the content in it? I have so far only this, but I can't become the filename in right way, I become only the last filename and not the content of this file.
public static List<Objekt> run() throws IOException {
String path2 = "D:\\folder\\files";
File folder = new File(path2);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++){
if (listOfFiles[i].isFile()){
files = listOfFiles[i].getName();
if (files.endsWith(".csv")){
files = files.replace(".csv", "");
System.out.println(files);
}
}
}
List<Objekt> lines = new ArrayList<Objekt>();
String csvString = "D:\\folder\\files\\file1.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
Objekt objekt = null;
String[] hdr = null;
int l_count = 0;
br = new BufferedReader(new FileReader(csvString));
while ((line = br.readLine()) != null) {
if (l_count == 0) {
hdr = line.split(cvsSplitBy);
}
else{
String[] temp = line.split(cvsSplitBy);
for (int i = 0; i < temp.length; i++) {
objekt = new Objekt();
objekt.setTimestamp(hdr[i] + "\t" + temp[0] + "\t"
+ temp[i] + "\t" + files + "\n");
lines.add(objekt);
}
System.out.println(lines);
}
l_count++;
}
br.close();
return lines;
}
This is what I become (I get only that filename, which is at the end of the folder).
>tr_klue 06.03.2014 11:30 1389 outfilename
>tr_klue_lo 06.03.2014 12:00 1889 outfilename
but I need all filenames in this folder with corresponding content and save these in subfolder with filename and datetime with time when this was read, like:
tr_klue 06.03.2014 11:30 1389 outfilename
>tr_klue_lo 06.03.2014 12:00 1889 outfile1
>tr_klue 06.03.2014 12:30 100 props2
>tr_klue_lo 06.03.2014 13:00 89 colorak
Can you please give me some suggestions in which way to go?

If I understand your question, you need to first build a List of files and then iterate it -
File[] fileArray = folder.listFiles();
List<String> files = new ArrayList<String>(); // <-- A list of files
for (int i = 0; i < fileArray.length; i++)
{
if (fileArray[i].isFile())
{
String fileName = fileArray[i].getName();
if (fileName.endsWith(".csv")) // <-- does it end in ".csv"?
{
files.add(fileName); // <-- Add the file to the List.
}
}
}
// Now files contains the matching fileNames...
for (String fileName : files) {
// Add code here to use each fileName
System.out.println(fileName.replace(".csv", ""));
}

Related

Searching a directory for a file name

How to search a particular folder for a file name, that is input by the user. In my program the file is an excel spreadsheet. So if i basically use:
Scanner kbReader = new Scanner(System.in);
String fileName = kbReader.nextLine();
How would i search and open the corresponding file with the name fileName.
You need to use regular expression to match your file name like filename.matches("*"+expectedfilename+"*.xls")) on List of file names taken from directory.
String fileName = null;
File folder = new File("your/directory/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
fileName = listOfFiles[i].getName();
if(fileName.matches("*"+expectedfilename+"*.xls"))){ // put regex here
// do your code here and
// if you want to open do operation on file then file object
File file = listOfFiles[i];
}
}
}
Try this
File dir = new File("F:/");
File[] allFileName = dir.listFiles();
for (int i = 0; i < allFileName.length; i++) {
String filename = allFileName[i].getName()
if (allFileName[i].isFile()) {
if (filename.endsWith(".xls"))
System.out.println("This is a excel file with name " + filename);
}
}

Java - Renaming a file automatically after searching a directory

When I run this program, it finds the file that starts with yyyy and returns the files correctly; however, it skips my.File.exists() and goes to else "File Name Change Failed". I have been looking at this code for a long time..what noob mistake am I making?
//Searches the path for files
String pathToScan =("C:\\Users\\desktop\\test\\");
String target_file ;
File folderToScan = new File(pathToScan);
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
if (target_file.startsWith("YYYY")){
System.out.println("-----------------------------------------------");
System.out.println("Match Found: "+ target_file);
//if the target file exists
if(myFile.exists()){
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File("C:\\Users\\desktop\\test\\"+lastmodi+".csv");
//If rename successful, then print success with file location
if(myFile.renameTo(newfile)){
System.out.println("File Name Change Successful, New File Created:" + newfile.getPath());
}
else{
System.out.println("File Name Change Failed");
}
}
I think you are referring a wrong file in myFile. The following code is working for me with added code. The other reasons can be that you don't have the Access to Write in C:\Users\desktop\test\ directory and/or that directory doesn't exist.
String pathToScan = ("C:\\Users\\<User Name>\\desktop\\test\\");
String target_file;
File folderToScan = new File(pathToScan);
File myFile = null; // Added this
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
myFile = listOfFiles[i]; // Added this
if (target_file.startsWith("YYYY")) {
System.out
.println("-----------------------------------------------");
System.out.println("Match Found: " + target_file);
// if the target file exists
if (myFile.exists()) {
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat(
"YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File(
"C:\\Users\\<User Name>\\desktop\\test\\"
+ lastmodi + ".csv");
// If rename successful, then print success with file
// location
if (myFile.renameTo(newfile)) {
System.out
.println("File Name Change Successful, New File Created:"
+ newfile.getPath());
} else {
System.out.println("File Name Change Failed");
}
}
}
}
}

Java Files.copy Multiple Files, Different Names, Same Contents

I am using "Files.copy" to copy files from one directory to another. 1 file will work, but when transferring multiple files, the contents of the copied files are the same, but the names are different. Please ignore bad naming. I am just quickly testing.
private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.showOpenDialog(null);
PathFile = fc.getSelectedFile().getAbsolutePath();
files = fc.getSelectedFiles();
int i=files.length;
System.out.print(i);
filesPath = Arrays.toString(files);
txtPath.setText(PathFile);
}
private void btnMoveActionPerformed(java.awt.event.ActionEvent evt) {
InputStream inStream = null;
OutputStream outStream = null;
String text = txtPath.getText();
String[] list = filesPath.split(",");
//String extension = filename.substring(filename.lastIndexOf('.'), filename.length());
String destPath = txtDest.getText();
try {
for(int i = 0; i<list.length; i++){
String filenamePre = list[i]
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "");
String filename = filenamePre.substring(filenamePre.lastIndexOf('\\'), filenamePre.length());
System.out.println(filename);
File afile = new File(text);
//File bfile = new File(destPath+"\\file1"+extension);
File bfile = new File(destPath + filename);
Path pa = afile.toPath();
Path pb = bfile.toPath();
//inStream = new FileInputStream(afile);
//outStream = new FileOutputStream(bfile);
//byte[] buffer = new byte[1024];
//int length;
//copy the file content in bytes
// while ((length = inStream.read(buffer)) > 0) {
// outStream.write(buffer, 0, length);
//}
//inStream.close();
//outStream.close();
Files.copy(pa, pb, REPLACE_EXISTING);
//delete the original file
//afile.delete();
}
System.out.println("File(s) copied successful!");
System.out.println();
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
private void txtPathActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnOpenDestActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
//guiMove frame = new guiMove();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
PathDest = fc.getSelectedFile().getAbsolutePath();
txtDest.setText(PathDest);
}
shouldn't the getText method be in your loop when you retrieve the new file?
You are transferring only one file multiple times.
File afile = new File(text);
Source (text) is not changing in loop.
i am not sure what is your filePath content
String[] list = filesPath.split(",");
if you have two text box ( source directory and Destination directory) to get the source and destination .
Then you can get list of files from source like this.
File[] fList = new File(sDir).listFiles();
and loop through flist to get the files like this.
public void fileCopy(String sourceDir , String destDir) throws IOException{
File sDir = new File(sourceDir);
if (!sDir.isDirectory()){
// throw error
}
File dDir = new File(destDir);
if (!dDir.exists()){
dDir.mkdir();
}
File[] files = sDir.listFiles();
for (int i = 0; i < files.length; i++) {
File destFile = new File(dDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "")
.replace(" ", ""));
// destFile.createNewFile();
Files.copy(files[i], destFile);
}
}

ArrayIndexOutOfBoundsException - when parsing a csv file

I want to transform a csv file. My file looks like that:
I am using the opencsv libary to parse my csv. That is my run method to parse the file:
public void run() throws Exception {
CSVReader reader = new CSVReader(new FileReader(csvFile), ';');
String [] nextLine;
int i = -1;
String fileName = "";
String companyName = "";
String currency = "";
String writerPath;
List<String> returnList = null;
List<String> dateList = null;
while ((nextLine = reader.readNext()) != null && i < 10) {
String[] line = nextLine;
System.out.println(line[0]);
System.out.println(line);
i++;
//fileName of the String
if(!line[0].contains("NULL")) {
fileName = line[0];
}
writerPath = "C:\\Users\\Desktop\\CSVOutput\\" + fileName + ".csv";
//write csv file
CSVWriter writer = new CSVWriter(new FileWriter(writerPath), ';');
//write Header
String[] entries = "Name;Date;TotalReturn;Currency".split(";");
writer.writeNext(entries);
//create Content
//companyName of the String
if(!line[1].contains("Name")) {
companyName = line[1];
System.out.println(companyName);
}
//currency
if(!line[2].contains("CURRENCY")) {
currency = line[2];
}
//total returns
returnList = new ArrayList<String>();
if(line[0].contains("NULL")) {
for(int j = 3; j <= line.length; j++) {
returnList.add(line[j]); // EXCPETION COMES HERE!
}
}
//"Name;Date;TotalReturn;Currency"
List<String[]> data = new ArrayList<String[]>();
for(int m = 0; m <= line.length; m++) {
data.add(new String[] {companyName, "lolo", "hereComesTheDateLater", currency});
}
writer.writeAll(data);
//close Writer
writer.close();
}
System.out.println("Done");
}
}
I am getting an
java.lang.ArrayIndexOutOfBoundsException: 3039
at com.TransformCSV.main.ParseCSV.run(ParseCSV.java:78)
at com.TransformCSV.main.ParseCSV.main(ParseCSV.java:20)
at this line: returnList.add(line[j]);?
Why? What are possible ways to fix that?
I really appreciate your answer!
You want j < line.length and not <=. If there are 10 elements in an Array then there is not an item at index 10 - you only have 0-9.
Further using loads of variables and assigning them is not the preferred way to parse CSV. Java is an Object Orientated language.
Use an Object to represent each line and bind the line using the opencsv javabean API
You are parsing the file till length of file <= instead you have to use <. It will access the file till line.length - 1
Replace with this
for(int j = 3; j <line.length; j++) {
returnList.add(line[j]);
}

Directory not being recognized

So I have a method that reads all the files in a folder and creates new classes in a List with the variables read from the files. For some reason it doesn't ever get past the if(mainDir.isDirectory()){ part, even though the paths are correct and I double checked the folders were there.
public static void loadIntoClass(String dir, int temp){
try {
File mainDir = new File(dir);
if(mainDir.isDirectory()){ //Checks if the dir is a folder and not a file
String[] fileNames = mainDir.list(); //Grabs a list of all the filenames in the dir
for(int x = 0; x > fileNames.length; x++){ //loops through all the files
File currFile = new File(dir + fileNames[x]); //Creates the object we will be gathering information from
if(currFile.isFile()){ //Checks to make sure the file is a file and not a folder
BufferedReader br = new BufferedReader(new FileReader(currFile));
String line = br.readLine();
int currLoop = 1;
boolean collides = false;
while(line != null){ //Will keep checking files until it reaches a blank line
currLoop ++; //Keeps track of how many times it loops
test = line.split("="); //Splits up the variable from the declaration
String toString = test[0].trim(); //Trims off any extra blank spaces on either side
System.out.println("Reading: " + toString + " on line " + currLoop); //For debugging
String toString2 = test[1].trim(); //Trims the second string
parse[currLoop] = Integer.parseInt(toString2); //Turns the string into an integer then puts it into the array
if(toString.equalsIgnoreCase("Collides")){
if(toString2.equalsIgnoreCase("true")){
collides = true;
}
}
if(toString.equalsIgnoreCase("Image Path")){
//path = toString2;
}
line = br.readLine();
}
if(temp == 1){
types.add(new Type(parse[1], parse[2], parse[3], parse[4], parse[5], parse[6], parse[7]));
}
if(temp == 2){
tiles.add(new Tiles(parse[1], collides, null));
}
if(temp == 3){
abilities.add(new Abilities(parse[1], parse[2], parse[3], parse[4]));
}
br.close();
}
}
}
} catch(Exception e) {
System.err.println("ERROR: " + e);
}
}
After that if I change it some other path like "C:/test" it works only to freeze at the for loop. Here's the declaration:
loadIntoClass("C:/Program Files(x86)/GameNameHere/config/enemies", 1);
The methods isDirectory() and isFile() doe not work if the underlying FS-Objects do not exist.
There are multiple possible issues, which you are not taking into consideration...
Your not checking to see if the dir exists
Your not making sure to close your files in case of an read error (or other associated error)
You making life tough for yourself using File#list, instead use File#listFiles which will return an array of File
Make better use of exceptions...
For example...
public static void loadIntoClass(String dir, int temp) throws IOException {
File mainDir = new File(dir);
if(mainDir.exists) { // Check to see if the abstract path actually exists
if (mainDir.isDirectory()){ //Checks if the dir is a folder and not a file
File[] fileNames = mainDir.listFiles(); //Grabs a list of all the filenames in the dir
//String[] fileNames = mainDir.list(); //Grabs a list of all the filenames in the dir
if (fileNames != null && fileNames.length > 0) {
//for(int x = 0; x > fileNames.length; x++){ //loops through all the files
for(File currFile : fileNames){ //loops through all the files
//File currFile = new File(dir + fileNames[x]); //Creates the object we will be gathering information from
if(currFile.isFile()){ //Checks to make sure the file is a file and not a folder
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(currFile));
String line = null;
int currLoop = 1;
boolean collides = false;
while((line = br.readLine()) != null){ //Will keep checking files until it reaches a blank line
//...//
}
//...//
// Make sure you make all best attempts to close the reader...
} finally {
try {
br.close();
} catch (Exception exp) {
}
}
}
}
} else {
// You may not care, but...
throw new IOException(dir + " does not contain any files");
}
} else {
throw new IOException(dir + " is not a directory");
}
} else {
throw new IOException(dir + " does not exist");
}
}

Categories

Resources