Using path to load the file - java

this one thing just keeps coming back to me. I am trying to load the .csv file in Java and it looks like this:
public static List<String> getEntryList () throws IOException{
final String NAME = "test.csv";
final String PATH = "resources/csvFiles";
final Path path = FileSystems.getDefault().getPath(PATH, NAME);
return Files.readAllLines(path, Charset.forName("UTF-8"));
}
obviously not working. Gives me java.nio.file.NoSuchFileException: resources\csvFiles\test.csv exception, but works ok when I enter tehe full path on the drive. I tried using classpath but also didn't work. What is the proper way of doing this?

Try this:
InputStream is = YourClassName.class.getResourceAsStream("test.csv");

Related

Not able to move .gitignore file from one directory to another

I am automating a particular process where in one of the steps I need to copy a .gitignore file from one directory to another.
I am using Apache's FileUtils class to achieve the same, however it is not able to recognise this particular file (it is although present in the folder). The code is working for other files.
Here is my code:
public void copyFile(String destinationPath, String file) throws IOException {
ClassPathResource classPathResourceAPIUtils = new ClassPathResource(file);
String fileName = file.substring(file.lastIndexOf("/"));
InputStream inputStreamapiUtils = classPathResourceAPIUtils.getInputStream();
BufferedReader readUtils = new BufferedReader(new InputStreamReader(inputStreamapiUtils));
List<String> utilsLines = readUtils.lines().collect(Collectors.toList());
FileUtils.writeLines(new File(destinationPath+fileName), utilsLines, false);
}
Why are you rewriting the files. Just use:
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING)
or
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING)

Java. Selenium. File Uploading Another One

In my case, works below method.
I use Windows now, but after writing some tests, want transfer it to the *nix environment. And some cool guys says that path must be abstract one.
driver.findElement(By.id("admin_offer_kind_logo")).sendKeys("C:\\Path\\To\\File");
But of I try:
driver.findElement(By.id("admin_offer_kind_logo")).sendKeys(System.getProperty("user.dir")+"\\src\\test\\resources\\Koala.jpg");
or
driver.findElement(By.id("admin_offer_kind_logo")).sendKeys(System.getProperty("user.dir")+"/src/test/resources/Koala.jpg");
It doesn't wants to upload the goddamn file.
#Test
public void FileFinding() {
String file = System.getProperty("user.dir");
System.out.print("FilePath: ");
System.out.println(file);
}
Above code prints: FilePath: C:\SeleniumTests\FirstWebDriverTest
Full path to my file in project is:
C:\SeleniumTests\FirstWebDriverTest\src\test\resources\Koala.jpg
You can use com.google.common.io.Resources to get the file from your resources folder.
String filePath = "Koala.jpg";
URL resource = Resources.getResource(filePath);
String uploadFullPath = resource.toURI().getPath();
Or refer the logic from How to get the path of src/test/resources directory in JUnit?
With help of one good man, found two working methods:
#Test
public void FileFinding_Right_One() {
String file = getClass().getClassLoader().getResource("Koala.jpg").getFile();
System.out.println(file.substring(1,file.length()));
}
#Test
public void File_Finding_Right_Second
File f = new File("src/test/resources/Koala.jpg");
System.out.println(f.getAbsolutePath());
}

Inputting a text file into a program?

I had a lecture today on inputting and outputting but it didn't really seem to explain where the text file is etc..
here is my code:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I get a file not found exception but the text file is in the same folder as the program?
Please first read up on the difference between relative and absolute paths. An absolute path is:
C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\lab1task3.txt
A relative path would be just "lab1task3.txt", which is what is given. That means that lab1task3.txt can be found relative to the working directory (e.g if the working directory was "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" then it would find it).
However, you could also use an absolute path, but remember that doing so means that it will only work if a file is in the same place on the machine running it. E.g, if you submit with "C:\Users\Ceri\workspace1\inputoutput\src\inputoutput\" in your code then it will only work if someone else has that same file and location on their computer. Please note that if this is an assignment, the module convenor/marker probably does not have afolder called C:\Users\Ceri.... If you submit your work using a relative path, anyone using your code just needs to make sure the file is relatively in the same place (e.g in the same folder).
If this doesn't matter, you need to escape the back slash characters with another back slash in the path. This should work:
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
String name;
int lineCount = 0;
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt");
Scanner in = new Scanner(input);
while(in.hasNextLine()){
lineCount++;
}
System.out.println(lineCount);
}
}
I notice you are using eclipse. Your "working directory" is your workspace. Therefore you want to move your file to:
C:\Users\Ceri\workspace1\inputoutput\lab1task3.txt
This should work for you using a "relative" path which you had in your opening post.
You're confusing class file location and the "user's working directory", the latter being what Java uses to determine the root of the file path (unless absolute paths are needed), and you can find its location easily via:
System.out.println(System.getProperty("user.dir"));
I advise you to forgo use of files altogether when all you need to do is read in data, and instead get the text file as a program resource:
// where you swap the name of your class for MyClass
InputStream fileResource = MyClass.class.getResourceAsStream("myFile.txt");
Scanner scanner = new Scanner(inputStream);
Note that if you must use a File, then find out what the user's working directory is, as shown above, and then tailor your file path so that it is relative to this working directory.
Try:
File file = new File("src/inputoutput/lab1task3.txt");
My guess is that your current working directory is not the same place as the project location. If your working directory were, the file would definitely be found if it does indeed have that name.
To workaround this issue you can always be using a InputStream instead, like so:
InputStream inputStream = new InputStream("lab1task3.txt");
Scanner scanner = new Scanner(inputStream);
If you want to see your current working directory you can use something like this:
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
}
}

Can't save file in tomcat webapp running on a linux server

Im currently debugging a webapp, where the user is supposed to upload a file which is then stored temporarily on the server and send via E-Mail to an administrator.
The app runs on a tomcat 8 in a linux server environment. The class from where the error occurs looks like follows:
#Service
public class BugReportBo implements IBugReportBo {
...
#Value("${app.temp.folder}")
private Resource temp;
...
private File byteArrayToFile(final byte[] lob, final String string) throws IOException {
final int locatorStartPos = 6;
String uri = temp.getURI().toString().substring(locatorStartPos);
//uri: var/lib/tomcat/webapps/prototype/res/temp/
//string: temp0.jpg
// convert array of bytes into file
File f = new File(uri + string);
FileOutputStream fileOuputStream = new FileOutputStream(uri + string);
fileOuputStream.write(lob);
fileOuputStream.close();
return f;
}
}
The error is thrown from FileOutputStream fileOuputStream = new FileOutputStream(uri + string);.
The Exception is a FileNotFoundException (message:"var/lib/tomcat/webapps/prototype/res/temp/temp0.jpg (Datei oder Verzeichnis nicht gefunden)").
Everything seems to be ok to me as the folder is where it is supposed to be and the path seems to be fine as well.
Any ideas?
var/lib/tomcat/webapps/prototype/res/temp/temp0.jpg
You forget the first '/', so the path is understand like a relative path, instead of an absolute path.
/var/lib/tomcat/webapps/prototype/res/temp/temp0.jpg

Create directory using a variable as the name

Maybe its something simple i am over looking, but i need to be able to create sub directories using a list of numbers stored in a txt file. When i use a string literal it creates the directory, but when i switch to using the variable being used for the items in the list it will not. Here is the code block.
private static void GetJarDir() throws URISyntaxException {
CodeSource codeSource = NewJFrame.class.getProtectionDomain().getCodeSource();
File jarFile = null;
jarFile = new File(codeSource.getLocation().toURI().getPath());
jarDir = jarFile.getParentFile().getPath().replace("dist", "").replace("build", "");
mainFolder = jarDir + "Invoices\\";
}
this is the method i use to get the directory for the jar file and append the path with the directory i need to create the sub-directories in, i'm sure this works.
BufferedImage dest = image.getSubimage(0, 3377, 465, 80);
String newDir = new OCR().recognizeEverything(dest);
File theDir = new File(mainFolder + newDir);
new File(mainFolder + newDir.mkdirs();
im using an optical character recognition library to grab an invoice number off of a cropped image. So newDir is the invoice number. Ive printed out the path and it is the correct path, it is just not creating the directory. If i change the variable to the actual invoice number it works, any ideas?
new File(mainFolder + "223545").mkdirs();
so sitting here playing with it ive narrowed the problem down to the string returned from the OCR. It has to be a string or it wouldnt compile...but when i try to parse the string to an int it throws an exception. and it is in fact an integer

Categories

Resources