Eclipse can't find/open text files from path - java

I'm currently making an app which reads from text files and then does cool stuff with the words inside it. Now I unfortunately have the problem that Eclipse can't seem to find/open the text files. Since this is my first app I am not 100% sure if I did the whole "putting-files-in-eclipse"-thing correctly.
Here are two screenshots that pretty much sum up the whole problem:
Error message when the method is executed
My directories look like this.
I already wrote another program where I used similar pathing and everything worked fine.
Here's the code: (elemArray contains "wi", "wa", "f", "l", "d")
String[] elemArray = elems.toArray(new String[0]);
for(int i = 0; i < 5; ++i){
for(int l = 3; l < 6; ++l){
checkFile = new Scanner(new File("texts/" + elemArray[i] + "monster" + l + ".txt")).useDelimiter(",\\s*");
.
.
. does some other irrelevant stuff here
What am I doing wrong?

From the available information I suspect a working directory mismatch.
Working Directory
Your working directory when launching your Java program is not what you expect. The new File("texts/" [...] will create a relative path.
You can specify the working directory in the Launch Configuration in the Arguments tab near the bottom in the Working directory: section:
Test/Debug
Extract the new File("texts/" [...] to a variable (it is quite a long line as it is). You can add an expression of f.getAbsoluteFile() to ensure it resolves as expected.
i.e. rewrite like this (I would probably extract the string passed to new File() too BTW):
String[] elemArray = elems.toArray(new String[0]);
for(int i = 0; i < 5; ++i){
for(int l = 3; l < 6; ++l){
File f = new File("texts/" + elemArray[i] + "monster" + l + ".txt");
checkFile = new Scanner(f).useDelimiter(",\\s*");

Related

Get value from website but java code does not work. how to fix?

My code is not working. it gives error for this line "int temp = Integer.parseInt(currentTemp.substring(0, currentTemp.indexOf("˚ ")));" I tried several ways but I could not. Maybe a different factor affects it. Is there any idea to fix it?
Error is here:
Background: # darksky.feature:5
Given I am on Darksky Home Page # DarkskySD.iAmOnDarkskyHomePage()
Current Temp: 43°
Current Temp:43˚ Rain.
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at framework.DarkskyTS.etr(DarkskyTS.java:138)
at stepdefinition.DarkskySD.currentTempGreaterOrless(DarkskySD.java:39)
at ✽.Then I verify current temp is not greater or less then temps from daily timeline(darksky.feature:25)
#currenttempgreaterorless
Scenario: Verify Current Temperature should not be greater or less than the Temperature from Daily Timeline # darksky.feature:24
Then I verify current temp is not greater or less then temps from daily timeline # DarkskySD.currentTempGreaterOrless()
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at framework.DarkskyTS.etr(DarkskyTS.java:138)
at stepdefinition.DarkskySD.currentTempGreaterOrless(DarkskySD.java:39)
at ✽.Then I verify current temp is not greater or less then temps from daily timeline(darksky.feature:25)
Failed scenarios:
darksky.feature:24 # Scenario: Verify Current Temperature should not be greater or less than the Temperature from Daily Timeline
1 Scenarios (1 failed)
2 Steps (1 failed, 1 passed)
0m5.234s
public void tempValue(){
String currentTemp = SharedSD.getDriver().findElement(By.cssSelector(".summary.swap")).getText();
System. out.println("Current Temp:" + currentTemp);
List<WebElement> tempsInTimeLine = SharedSD.getDriver().findElements(By.cssSelector(".temps span:last-child"));
int temp = Integer.parseInt(currentTemp.substring(0, currentTemp.indexOf("˚ ")));
int highestInTimeLine = temp;
int lowestInTimeLine = temp;
for (WebElement tempInTime: tempsInTimeLine) {
String sLIneTemp = tempInTime.getText();
int lineTemp = Integer.parseInt(sLIneTemp.substring(0, sLIneTemp.indexOf("˚ ")));
if (lineTemp > highestInTimeLine){
highestInTimeLine = lineTemp;
}
if (lineTemp < lowestInTimeLine ){
lowestInTimeLine = lineTemp;
}
//int lineTemp = Integer.parseInt(sLIneTemp.substring(0, sLIneTemp.indexOf("˚ ")));
}
System. out.println("Highest Temp:" + highestInTimeLine);
System. out.println("Lowest Temp:" + lowestInTimeLine );
}
Instead of using indexOf("° "), try using indexOf("°"). It will work. The space you are putting after the degree symbol is unnecessary.
That message is telling you that "˚ " cannot be found in the string you are trying to parse. Like #Ashish, I suspect this is caused by the space after your degree symbol. Your new line should look like:
int lineTemp = Integer.parseInt(sLIneTemp.substring(0, sLIneTemp.indexOf("˚")));
Here is answer the question:
driver.get("https://darksky.net/forecast/40.7127,-74.0059/us12/en");
String currentTemp = driver.findElement(By.cssSelector(".summary.swap")).getText();
System.out.println("Current Temp:" + currentTemp);
List<WebElement> tempsInTimeLine = driver.findElements(By.cssSelector(".temps span:last-child"));
int temp = Integer.parseInt(currentTemp.substring(0, 2));
int highestInTimeLine = temp;
int lowestInTimeLine = temp;
for (WebElement tempInTime: tempsInTimeLine) {
String sLIneTemp = tempInTime.getText();
int lineTemp = Integer.parseInt(sLIneTemp.substring(0, 2));
if (lineTemp > highestInTimeLine){
highestInTimeLine = lineTemp;
}
if (lineTemp < lowestInTimeLine ){
lowestInTimeLine = lineTemp;
}
}
System.out.println("Highest Temp:" + Integer.toString(highestInTimeLine));
System.out.println("Lowest Temp:" + Integer.toString(lowestInTimeLine ));
I ran into the same issue. I am not sure whether my environment is the issue or not.
When I debugged that indexOf("°") call, I saw that it thought the parameter is "°" rather than just "°". I changed it to '°' and it worked.
However, when running mvn clean install, I noticed a warning -
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
So the file was UTF-8 (not sure whether it had a BOM or not) and was misinterpreted by Maven.
Going to their FAQ, they suggest to add -
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
under <properties>.
I added it, ran git checkout -- path/to/file.java to get the original code/encoding and re-ran mvn clean install.
The warning was no longer emitted and the issue was fixed.

How to JGit blame a file before commit?

Context: My merge ran into conflicts and I have a file like this example:
Foo.txt (merged)
1
<<<<<< HEAD
2-master
======
2-side
>>>>>> df803849788fde47965b3dc8f07f07d48320ea9c
3
Question: In order to get the developers who actually changed the conflicting lines, how to blame result file (above) prior to the commit? It works for git blame Foo.txt
Problem: I tried to do the following, but the blame is null inside the loop.
MergeResult m = runMerge(aScenario);
BlameCommand blamer = new BlameCommand(git.getRepository());
BufferedReader br = new BufferedReader(new FileReader(new File(mergedfilepath)));
BlameResult blame = blamer.setFilePath(mergedfilepath).call();
for (int i = 0; (line= br.readLine())!=null ; i++) {
// the blame at this point is null.
PersonIdent person = blame.getSourceAuthor(i);
System.out.println(person.getName() + ": "+ line);
}
I think the source of the traversal should be the result contents.
Starting from there you can loop over the changed regions and ask for the author. For example:
BlameResult blameResult = git.blame().setFilePath( ... ).call();
int size = blameResult.getResultContents().size();
for( int i = 0; i < size; i++ ) {
System.out.println( blameResult.getSourceAuthor( i ) );
}
At least for lines added to the work directory version of the file, an author named Not Committed Yet is returned.
However, your code should be prepared cope with getSourceAuthor() returning null. The JavaDoc states that the return value may be null.

How To Decode Protocol Buffer String in .Java file

I've searched all around for name to call this, but i can't find any....
Its in a .java file sent to me by a friend(He Thought i would decode it straightaway), without knowing i'm also a noob of this....
This is the String data i want to decode without compiling the Java file.
String[] descriptorData = {
"\n0com/google/javascript/jscomp/function_" +
"info.proto\022\006jscomp\"\277\002\n\026FunctionInformati" +
"onMap\0223\n\005entry\030\001 \003(\n2$.jscomp.FunctionIn" +
"formationMap.Entry\0225\n\006module\030e \003(\n2%.jsc" +
"omp.FunctionInformationMap.Module\032\207\001\n\005En" +
"try\022\n\n\002id\030\002 \002(\005\022\023\n\013source_name\030\003 \002(\t\022\023\n\013" +
"line_number\030\004 \002(\005\022\023\n\013module_name\030\005 \002(\t\022\014" +
"\n\004size\030\006 \002(\005\022\014\n\004name\030\007 \002(\t\022\027\n\017compiled_s" +
"ource\030\010 \002(\t\032/\n\006Module\022\014\n\004name\030f \002(\t\022\027\n\017c" +
"ompiled_source\030g \002(\tB \n\034com.google.javas","cript.jscompP\001"
What you see there is if I'm not mistaken a piece of auto generated code that describes
message FunctionInformationMap {
repeated group Entry = 1 {
required int32 id = 2;
required string source_name = 3;
required int32 line_number = 4;
required string module_name = 5;
required int32 size = 6;
required string name = 7;
required string compiled_source = 8;
}
}
It's here
https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/function_info.proto
and the generated code here can be found for example here
https://code.google.com/p/closure-compiler/source/browse/gen/com/google/javascript/jscomp/FunctionInfo.java?name=v20140407
Ps: I just googled "com/google/javascript/jscomp/function_info.proto" but you can actually reverse the process. Hints here for example https://www.sysdream.com/reverse-engineering-protobuf-apps
I Simply solved this by using the System.Out.PrintIn to print out the string data to a TXT file...
That's It..
Thanks...

How to get previous revision CL in perforce

I am writing a program, where i have the CL ,from which I need to access the previoius revision CL of each file.
How can I get it ?
Code I have written till now is:
IChangelist cl = server.getChangelist(clId);
List<IFileSpec> files = cl.getFiles(true);
for(int i = 0; i < files.size() ; i++) {
IFileSpec fileSpec=files.get(i);
}
Revision specifiers can help you here (see 'p4 help revisions').
In particular, the previous revision of each of those files is the file as of the previous changelist.
So, since clId is the changelist you care about, compute change clPrev = (clId - 1), and then look for 'file#clPrev'.

Batch file renaming – inserting text from a list (in Python or Java)

I'm finishing a business card production flow (excel > xml > indesign > single page pdfs) and I would like to insert the employees' names in the filenames.
What I have now:
BusinessCard_01_Blue.pdf
BusinessCard_02_Blue.pdf
BusinessCard_03_Blue.pdf (they are gonna go up to the hundreds)
What I need (I can manipulate the name list with regex easily):
BusinessCard_01_CarlosJorgeSantos_Blue.pdf
BusinessCard_02_TaniaMartins_Blue.pdf
BusinessCard_03_MarciaLima_Blue.pdf
I'm a Java and Python toddler. I've read the related questions, tried this in Automator (Mac) and Name Mangler, but couldn't get it to work.
Thanks in advance,
Gus
Granted you have a map where to look at the right name you could do something like this in Java:
List<Files> originalFiles = ...
for( File f : originalFiles ) {
f.renameTo( new File( getNameFor( f ) ) );
}
And define the getNameFor to something like:
public String getNameFor( File f ) {
Map<String,String> namesMap = ...
return namesMap.get( f.getName() );
}
In the map you'll have the associations:
BusinessCard_01_Blue.pdf => BusinessCard_01_CarlosJorgeSantos_Blue.pdf
Does it make sense?
In Python (tested):
#!/usr/bin/python
import sys, os, shutil, re
try:
pdfpath = sys.argv[1]
except IndexError:
pdfpath = os.curdir
employees = {1:'Bob', 2:'Joe', 3:'Sara'} # emp_id:'name'
files = [f for f in os.listdir(pdfpath) if re.match("BusinessCard_[0-9]+_Blue.pdf", f)]
idnumbers = [int(re.search("[0-9]+", f).group(0)) for f in files]
filenamemap = zip(files, [employees[i] for i in idnumbers])
newfiles = [re.sub('Blue.pdf', e + '_Blue.pdf', f) for f, e in filenamemap]
for old, new in zip(files, newfiles):
shutil.move(os.path.join(pdfpath, old), os.path.join(pdfpath, new))
EDIT: This now alters only those files that have not yet been altered.
Let me know if you want something that will build the the employees dictionary automatically.
If you have a list of names in the same order the files are produced, in Python it goes like this untested fragment:
#!/usr/bin/python
import os
f = open('list.txt', 'r')
for n, name in enumerate(f):
original_name = 'BusinessCard_%02d_Blue.pdf' % (n + 1)
new_name = 'BusinessCard_%02d_%s_Blue.pdf' % (
n, ''.join(name.title().split()))
if os.path.isfile(original_name):
print "Renaming %s to %s" % (original_name, new_name),
os.rename(original_name, new_name)
print "OK!"
else:
print "File %s not found." % original_name
Python:
Assuming you have implemented the naming logic already:
for f in os.listdir(<directory>):
try:
os.rename(f, new_name(f.name))
except OSError:
# fail
You will, of course, need to write a function new_name which takes the string "BusinessCard_01_Blue.pdf" and returns the string "BusinessCard_01_CarlosJorgeSantos_Blue.pdf".

Categories