Can't access indexes other than 0 - java

I'm trying to write a program to quickly rename some files in a folder.
The files are named like this:
C:\Users\user\Documents\Reports\Report FirstName LastName.FileNameExtension
I'd like to rename them like this:
C:\Users\user\Documents\Reports\Report LastName FirstName.FileNameExtension
This is my code so far:
public class FileRenamer {
public static void main(String[] args) {
List<String> filePaths = new ArrayList<String>();
try(Stream<Path> paths = Files.walk(Paths.get(args[0]))) {
paths.forEach(filePath -> {
filePaths.add(filePath.toString());
});
} catch (IOException e) {
e.printStackTrace();
}
filePaths.forEach(filePath -> {
String[] splitPath = filePath.split(" ");
String fileNameExtension = splitPath[2].split(".")[1];
splitPath[2] = splitPath[2].split(".")[0];
String newFilePath = splitPath[0] + " " + splitPath[2] + " " +
splitPath[1] + "." + fileNameExtension;
new File(filePath).renameTo(new File(newFilePath));
});
}
}
My problem is that it keeps throwing an ArrayIndexOutOfBoundsException for the splitPath array. But it doesn't throw an exception when I'm running a for-loop to output the indexes from 0 to 2. What am I doing wrong?
EDIT: This is the working for-loop
for(int i = 0; i < splitPath.length; i++) {
System.out.println(i + ": " + splitPath[i]);
}
It outputs this to the console:
0: C:\Users\user\Documents\Reports\Report
1: FirstName
2: LastName.FileNameExtension

Files.walk() not only prints the regular files in the directory, but also the directory itself and any hidden files. Those will likely not fit your pattern.
Files.walk(Paths.get("/home/joost"), 1).forEach(p -> System.out.println(p.toString()));
/home/joost
/home/joost/someRegularFile.jpg
/home/joost/.profile
...
Also, Path::toString() gives to the full path, not just the filename. So if any of the directories in your path has a space in it, you will get unexpected results.

Related

Looping Main Method while Writing Output Data to TXT File

So, I am working on a java project that is concerned with genetic algorithm.
I have a main method that calls a function (Let's call it function 1) that calculates through until the specified iterations. I wanted to run the main method 100 times and collect the data, so I decided to use FileWriter inside the function 1 that I am calling in my main method.
public static int Runcnt = 0;
static int o = 0;
public static File statText = new File("C:\\Users\\ShadyAF\\Desktop\\StatTest.txt");
public static void main(String [] args){
while(Runcnt <= 100)
{
final long startTime = System.nanoTime();
MainAlgorithm mA = new MainAlgorithm("config.xml");
mA.cMA();
final long duration = System.nanoTime() - startTime;
System.out.println(duration/1000000000 + " seconds");
o = 0;
}
The above snippet of code is the main that I'm trying to loop. (function 1)
System.out.println("best = "+Main.indx+" = "+Main.val);
System.out.println("max_cnt: " + Main.max_cnt);
try {
FileOutputStream is = new FileOutputStream(Main.statText);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("#" + Main.Runcnt + " Best#: " + Main.indx + " BestScore: " + Main.val + " MaxCnt: " + Main.max_cnt + "\n");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to file.");
}
The above snippet of code is the mA.cMa() function that is inside the main loop.
I ran the code for a while and it appears that the program writes to the file only for the first loop and does not do anything for the rest of the looops.
Any help is much appreciated!
Edit: Why am I getting downvoted? At least leave a helpful comment :/
You should change your pattern from scratch... anyway you can try with something like this in your Main:
public static Path pathFile = Paths.get("C:\\Users\\..blah..\\stats.txt");
Then use in your loop
try {
String log = "#" + Main.Runcnt + " Best#: " + Main.indx + " BestScore: " + Main.val + " MaxCnt: " + Main.max_cnt + "\n";
Files.write(Main.pathFile, log.getBytes(), Files.exists(Main.pathFile) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);
} catch (IOException e) {
// exception handling
}
It is not so efficient, in particular in case of lot of records but whole code you wrote should need strong refactoring too :)

while loop needs to continue

I have this code
static String sCurrentLine = null;
/* keyword */
static String keyword = null;
Scanner keywordFile = null, siteFile = null;
try {
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
siteFile = new Scanner(new FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
keyword = keywordFile.nextLine().trim();
while (sCurrentLine != null){
while (keywordFile.hasNext() || keyword == null) {
System.out.println("Line--> " + keyword);
System.out.println("Current here >>" + sCurrentLine);
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
keyword = keywordFile.nextLine();
System.out.println("next keyword " + keyword);
///* reset search to top of site file */
siteFile = new Scanner(new
FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
}
else {
sCurrentLine = siteFile.nextLine();
if (sCurrentLine == null) {
break;
}
if (!sCurrentLine.matches(keyword)){
System.out.println("The following keyword " + keyword + " does not exist in file "
+ fileChooser.getSelectedFile());
}
}
} //2nd while loop
}
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
siteFile.close();
keywordFile.close();
}
and i have a text file called keywords which has a list of keywords in it,
but my logic is off an I cannot figure out why.
I think I may need to run the loop one last time but not sure how to do that
My issue is that the last word in the keyword file never gets read in. so the program stops at the 2nd to last element in the text file.
I am not sure that I understand what your code should do.
If I understood correctly your code, your task is to read keywords from a file with keywords and then find all keywords in another file. Is it correct?
You should separate reading keywords from the file and search for them in the file. You should 'load' keywords in a list and then search through the file.
To load keywords in list
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
List<String> keywordsList = new ArrayList<>();
while (keywordFile.hasNextLine()) {
keywordsList.add(keywordFile.nextLine());
}
And to search for keywords in the file
siteFile = new Scanner((Readable) new FileReader(fileChooser.getSelectedFile()));
while (siteFile.hasNextLine()) {
String sCurrentLine = siteFile.nextLine().trim();
for (String keyword : keywordsList) {
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
break;
}
}
System.out.println(
"The following keyword " + keyword + " does not exist in file " + fileChooser.getSelectedFile());
}
I hope this will help :)

Request parameters coming from jsps are changed when two different users access the code same time

public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.

Java program, int i (i=0) default value is being used despite it increasing by 1 each loop

I am creating a JAVA program to copy certain folders to a new location automatically, to do this I created a function with a loop to use the same function for each given folder source and destination. The problem is that the function will just copy the first folder to the new location multiple times instead of copying it once then copying the next folder. The folder locations are held in a string array and a specific one is selected by changing value [i]. Each time the function loops [i] increases but the loop does not select the [i] value as well as the next folder to copy.
Is anyone able to help me with this, the code i am working with is below, Thanks.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Application {
static String[] saves = {
"C:\\Users\\Lucas\\Documents\\My Games\\Halo",
"C:\\Users\\Lucas\\Documents\\My Games\\Terraria",
"C:\\Users\\Lucas\\Documents\\My Games\\Borderlands 2",
"C:\\Users\\Lucas\\Documents\\My Games\\Rocket League"
};
private static int i = 1;
File source = new File(saves[i]);
static File folder = new File("Saves\\");
File dest = new File(String.valueOf(folder) + "\\" + source.getName());
private void Start() throws IOException {
MakeDirectory(folder);
Copy();
}
private void Copy() throws IOException {
copyFileUsingJava7Files(source, dest);
Add();
}
private void Add() throws IOException {
i++;
System.out.println("Value of i = " + i);
System.out.println("");
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
if (!dest.exists()) {
System.out.println("Copying files from: " + "'" + source + "'");
System.out.println("");
copyFolder(source, dest);
System.out.println("File copied");
} else {
copyFolder(source, dest);
}
}
private static void copyFolder(File source, File dest) throws IOException {
if (source.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory created :: " + dest);
}
String files[] = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
if (source.lastModified() > dest.lastModified()) {
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + dest);
} else {
System.out.println("A newer version exists of: " + "'" + dest + "'");
}
}
}
private static void MakeDirectory(File folder) {
if (!folder.exists()) {
System.out.println("Creating directory: " + "'" + folder + "'");
folder.mkdir();
System.out.println("Directory created");
} else {
System.out.println("Directory already exists: " + "'" + folder + "'");
}
}
public static void main(String[] args) throws IOException {
Application app = new Application();
int l;
for (l = 0; l < 3; l++) {
app.Start();
}
}
}
It doesn't look like you're ever changing the source field after setting it initially. You're setting it to the second file, but then not changing it later. Incrementing i won't automatically update source because source is just a File.
Also, you're starting with i = 1. In Java, arrays are zero-indexed, which means that the first item in the array is actually item 0, so you should be starting with i = 0 instead.
You have to reinitialize File source each time, you increase i. Otherwise, the source won't be changed.
Since i is a static variable, all objects share the same variable. Since you are incrementing the i during each app.Start() method, at the end of calling 5 times, its value is 5. Consequently you get the output as 5 in all your sys outs. Thats the point of static.

What is wrong in my code logically?

I am working on a code to rename number of files in java. I have a list of the files in a .txt. File in which my program retreives the name of the document and its new name. It currently does not work.. It compiles and run but it wont rename my files.
Here's my code:
public static void rename(String ol, String ne){
File oldfile =new File(ol);
File newfile =new File(ne);
int t=0;
if( oldfile.isFile() && oldfile.canRead()){
if (newfile.exists()){
t++;
ne = ne.substring(0,ne.lastIndexOf('.')) + " (" + t + ")" +
ne.substring(ne.lastIndexOf('.')) ;
rename(ol,ne);
}
if(oldfile.renameTo(newfile))
System.out.println("Rename succesful");
else
System.out.println("Rename failed" + " - " + ol + " " + ne);
}else
System.out.println("CANNOT Rename " + oldfile + " because read/write issues. Check
if File exists" );
}
public static void main(String[] args) throws IOException
{
ReadFile ren = new ReadFile("List of Founds.txt");
String r[] = ren.OpenFile();
for(int j=0; j<ReadFile.numberOfLines; j++){
String pdfOldName = r[j].substring(0,r[j].lastIndexOf('.'));
String pdfNewName = r[j].substring((r[j].lastIndexOf('.') + 4));
rename(pdfOldName, pdfNewName);
}
}
This is the 'List of founds' .txt file, the old name is on the left and the new name is on the right.
test.pdf.txt ayo1
test2.pdf.txt ayo2
test3.pdf.txt ayo3
You can use the File.html#renameTo(java.io.File) to accomplish this.
Heres a quick sample program i wrote.
hope this puts you in right direction
public class FileMain {
static int i = 1;
public static void main(String[] args) throws Exception {
File file1 = new File("D:/workspace/dir");
renamefiles(file1);
}
private static void renamefiles(File file){
File files[] = file.listFiles();
for(File tempFile :files){
if(tempFile.isDirectory()){
renamefiles(tempFile);
}else{
System.out.println(tempFile.getName());
File renameFile = new File("sample-"+(++i)+".bck");
tempFile.renameTo(renameFile);
}
}
}
}
You need a !
if (newfile.exists())
to
if (!newfile.exists())
You also need to follow conventions. And Unit Test.

Categories

Resources