I have the requirement to read CSV file from src/test/resource folder.
I provided the file at the root level and it is working fine. But I want to put all these files in src/test/resource folder.
String fileName = "Phone_valid.csv";
File srcFile = new File(fileName);
String path = srcFile .getAbsolutePath();
// path = C:\D Drive\Orange Codebase\dabek-data-processing\Phone_valid.csv
String fileName = "\\src\\main\\resource\\Phone_invalid.csv";
File srcFile = new File(fileName);
String path = srcFile .getAbsolutePath();
// path= "C:\src\main\resource\Phone_invalid.csv"
I want that path should be
path = C:\D Drive\Orange Codebase\dabekdataprocessing\\src\main\resource\Phone_invalid.csv
Remove the first backslash. Does this work?
String fileName = "src\\main\\resource\\Phone_invalid.csv";
This should work.
File file= new File("src/test/resources/filename.txt");
Note Avoid Space in directory name like Orange Codebase
Try this code
import java.io.File;
public class MyClass {
public static void main(String[] args) {
String fileName = "src\\main\\resource\\Phone_invalid.csv";
File srcFile = new File(fileName);
String path = srcFile .getAbsolutePath();
System.out.println("Path: "+path);
}
}
Output of above code will be..
Path: E:\Orange Codebase\dabekdataprocessing\src\main\resource\Phone_invalid.csv
I achieved the same by using below code
String phonePath= "src/test/resources/Phone_valid.csv";
File srcFile = new FileSystemResource(phonePath).getFile();
String path = srcFile.getAbsolutePath();
// path = C:\D Drive\Orange Codebase\dabekdataprocessing\src\test\resources\Phone_valid.csv.
Now, I am able to access the file from src/test/resources folder.
Related
I need to insert a file to a path. However, the file name need to change to a specific name before inserted.
How can I change the name of the file before insert to path? As many resources online only able to change the file name after inserted. Online Resource for rename file
My code currently
String localPath = "c://Users/foody/Documents/write_file_local/";
String finalPath = localPath + file.getOriginalFilename();
File uploadPath = new File(finalPath);
if (!uploadPath.getParentFile().exists()) {
uploadPath.getParentFile().mkdirs();
}
//I think need to rename the file here before insert to path
byte[] bytes = file.getBytes();
Path path = Paths.get(finalPath);
Files.write(path, bytes);
Replace your code with this and update your "CustomName_ABC" with your new fileName.
String localPath = "c://Users/foody/Documents/write_file_local/";
String finalPath = localPath + "CustomName_ABC";
File uploadPath = new File(finalPath);
if (!uploadPath.getParentFile().exists()) {
uploadPath.getParentFile().mkdirs();
}
Files.copy(file.toPath(), uploadPath.toPath());
You can copy your old file to a new filePath (directory) by using Files.copy() method. It will take two parameters:
Old file path
New file path
When I use relative path, I can run my Java program from Eclipse. But when I run it as a JAR file, the path doesn't work anymore. In my src/components/SettingsWindow.java I have:
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/files/profile.ser"));
I get a FileNotFoundException.
My file directory looks like this:
file directory
What I've tried:
String filePath = this.getClass().getResource("/files/profile.ser").toString();
String filePath = this.getClass().getResource("/files/profile.ser").getPath();
String filePath = this.getClass().getResource("/files/profile.ser").getFile().toString();
And I'd just put filePath in new FileInputStream(filePath) but none of these work and I still get a FileNotFoundException. When I System.out.println(filePath) it says: files/profile.ser
I'm trying to get the path of src/files/profile.ser while I'm in src/components/SettingsWindow.java
You can get the URL to the class:
String path =
String.join("/", getClass().getName().split(Pattern.quote(".")))
+ ".class";
URL url = getClass().getResource("/" + path);
which will either yield "file:/path/to/package/class.class" or "jar:/path/to/jar.jar!/package/class.class". You either can work with the URL or use
JarFile jar =
((JarURLConnection) url.openConnection()).getJarFile();
and use jar.getName() to get the path to parse to get your installation directory.
To get the current JAR file path I use:
public static String getJarFilePath() throws FileNotFoundException {
String path = getClass().getResource(getClass().getSimpleName() + ".class").getFile();
if(path.startsWith("/")) {
throw new FileNotFoundException("This is not a jar file: \n"+path);
}
if(path.lastIndexOf("!")!=-1) path = path.substring(path.lastIndexOf("!/")+2, path.length());
path = ClassLoader.getSystemClassLoader().getResource(path).getFile();
return path.substring(0, path.lastIndexOf('!')).replaceAll("%20", " ");
}
How to write or read any type of file (for example .txt file) to a resources folder with the config.property file, but without using absolute path file.
I tried to solve this like below:
ClassLoader classLoader = Setting.class.getClassLoader();
Setting setting = new Setting();
try (InputStream resourceAsStream = classLoader.getResourceAsStream("config.properties")) {
setting.load(resourceAsStream);
}
String readFileName = setting.getValue("pathSource.txt");
String writeFileName = setting.getValue("outPutPathSourceFile.txt");
String s = System.getProperty("line.separator");
File readFile = new File("./src/main/resources" + File.separator + "pathSource.txt");
File writeFile = new File("./src/main/resources" + File.separator + "outPutPathSourceFile.txt");
However, I don't want using ./src/main/resources prefix.
If your file is located under resources you able to access it like:
File file = new File(classLoader.getResource(fileName).getFile());
if you are using Spring you can use ResourceUtils.getFile():
File file = ResourceUtils.getFile("classpath:fileName")
UPDATE:
If I understand correctly, you want to read file which located under your src/main/resources without relative path usage /src/main/resources.
I created small demo:
public class ReadResourceFile {
public static void main(String[] args) throws IOException {
String fileName = "webAutomationConfig.xml";
ClassLoader classLoader = ReadResourceFile.class.getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
System.out.println("File exists: " + file.exists());
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
}
}
Output:
File exists: true
<?xml version="1.0" encoding="utf-8"?>
<config>
<baseUrl>https://www.gmail.com</baseUrl>
</config>
Project structure:
Resources (files on the class path, possibly inside a jar)can be read, but are not intended to be written to. You can use them as template to create an inital copy on the file system. – Joop Eggen
How can i change the name of a file to match the original file and have extra txt in it, please see example below
Original
dataFile.txt
thisNameNeedsToMatchDataFile.txt (but also have ".Step2" added in before the .txt)
Desired output
dataFile.txt
dataFile.Step2.txt
Any help would be appropriated thank you in advanced.
How i understand your problem this is how i think the solution could look like
(java 7+)
public class FileConverter {
public static void main(String[] args) throws IOException {
FileConverter converter = new FileConverter();
File newFile1 = new File("c:/parent1/file1.dump");
File newFile2 = new File("c:/parent2/file2.dump");
converter.convert2Files(newFile1, newFile2);
}
private void convert2Files(File file1, File file2) throws IOException {
// compare if the 2 files have the same name
if(file1.getName().equalsIgnoreCase(file2.getName())){
String newName = file1.getName().substring(0, file1.getName().lastIndexOf('.'));
String newNameOriginal = newName + ".txt";
String newNameStep2 = newName + ".Step2.txt";
File newFileOriginal = new File(file1.getParent(),newNameOriginal);
File newFileStep2 = new File(file1.getParent(),newNameStep2);
Path file = file1.toPath();/* use file1 as source file */
Path to = Paths.get(file1.getParent());/* path to destination directory */
Files.copy(file, to.resolve(newFileOriginal.toPath()));
Files.copy(file, to.resolve(newFileStep2.toPath()));
}
}
}
I want to move inside a directory in Java but I don't know its name? Does Java provide any functionality to do so?
File srcFile = "C:/Entertainment/XXXXXXX/break.avi"
I am certain that there is only one directory inside Entertainment but I don't know its name. How can I move inside XXXXXXX directory to access any file inside it?
Any help?
Try,
File file = new File("C:/Entertainment");
File[] files = file.listFiles();
File srcDir = new File("C:/Entertainment/");
File srcFile = null;
for (File dirMember : srcDir.listFiles()) {
if (!dirMember.isDirectory()) {
continue; // we don't need regular files
}
if (dirMember.getName().equals(".")) {
continue; // we don't need this directory
}
if (dirMember.getName().equals("..")) {
continue; // we don't need the parent directory
}
// This is the one you need.
srcFile = new File(new File(srcDir, dirMember.getName()), "break.avi");
}
You could also use a FileFilter, e.g one from Commons IO
File dir = new File("C:/Entertainment/");
File[] files = dir.listFiles( DirectoryFileFilter.INSTANCE ); // returns all subdirs
srcFile = new File(files[0], "break.avi");
File srcFile = new File("C:\\Entertainment");
srcFile = new File(srcFile, srcFile.list()[0]);
srcFile = newFile(srcFile, "break.avi");
System.out.println(srcFile.getPath());
File outer= new File("C:/test");
File inner = outer.listFiles()[0];//if you are sure there is one
File[] listOfFilesInInnerMost = inner.listFiles();
System.out.println("Files: " + Arrays.asList(listOfFilesInInnerMost));
will print
Files: [C:\test\something\text (2).txt, C:\test\something\text (3).txt, C:\test\something\text.txt]