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
Related
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", " ");
}
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.
I am facing a problem but have not able to solve it yet. Let me share what I have done till now. I tried to delete a file using java.nio.file packages. And below is my code.
// directory will be dynamically generated.
String directory = fileDirectory+ "//" + fileName;
Path path = Paths.get(directory);
if (Files.exists(path)) {
Files.delete(path);
}
I generated the path correctly. But when Files.exists(path) calls it return false. That's why file is not deleted. But if I generated the directory string by hard-coded than it works perfectly.
// hard-coded directory works perfectly.
String directory = "C://opt//tomcat//webapps//resources//images//sprite.jpg";
I also tried the another method Files.deleteIfExists(path);. Which check the both the file existence and delete the file.
The other packages org.apache.commons.io.FileUtils and java.io.File have tried. But can't resolve the issue.
Note: My application is in spring-boot. And I read the directory from the application.properties file for both save images and delete images.
EDIT:
file uploading I mean save into the directory is perfectly worked. But file deletion does not work.
application.properties
image.root.dir=images
image.root.save.dir=C:/opt/tomcat/webapps/resources/
in implementation file
#Value("${image.root.dir}")
private String UPLOADED_FOLDER;
#Value("${image.root.save.dir}")
private String saveDir;
String directory = saveDir + UPLOADED_FOLDER + "/" + fileName;
save file into directory
String directory = saveDir + UPLOADED_FOLDER + "/";
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(directory);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
path = Paths.get(directory, file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
logger.error("save image into directory : " + e);
}
String directory = fileDirectory+ "//" + fileName;
This is not the correct separator used between a directory and a file name, though it seems to work as well.
This means the problem is not the separator, but a mismatch between the code that you use to generate the path and this code. You're generating the directory into somewhere else than where this is pointing.
I'm trying to upload a file from an HTML file input.
I am using Apache Commons FileUpload and the file uploads successfully. However, when I try storing the file path in my MySQL, it is storing it without file path code:
String uploadFolder = getServletContext().getRealPath("/");
String fileName = new File(item.getName()).getName();
filePath = uploadFolder+"/"+fileName;
File uploadedFile = new File(filePath);
This is how I'm trying to store the file.
sample filepath stored
C:UsersLashDesktopworkspace3.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebappsJavaECom/download doget.txt
I have no idea what this question is about, but the correct way to do the operations your posted code is doing is as follows:
File uploadFolder = new File(getServletContext().getRealPath("/"));
String fileName = new File(item.getName()).getName(); // not sure what's going on here
File uploadedFile = new File(uploadFolder, fileName);
How can I get file size in Java if I have a relative path to a file such as:
String s = "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with two diferent strings:
String[] separatedPath = s.split("/");
List<String> wordList = Arrays.asList(separatedPath);
String ret = "/" + wordList.get(1) + "/" + wordList.get(2) + "/" + wordList.get(3)+ "/" + wordList.get(4);
s = ret;
In this case s="/documents/19/21704/file2.pdf";
In second case s="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with:
File file1 = new File(s);
long filesize = file1.length();
and with:
String filePath = new File(s).toURI().getPath();
File file2 = new File(filePath);
long filesize2 = file1.length();
and also with (if the problem is in not providing full path):
String absolutePath = FileUtil.getAbsolutePath(file1);
File file3 = new File(absolutePath);
long filesize3 = file3.length();
byte[] bytes1=FileUtil.getBytes(file1);
byte[] bytes2=FileUtil.getBytes(file2);
byte[] bytes3=FileUtil.getBytes(file3);
I am always getting in debug that filesizes in all cases are 0.
Maybe is worth noticing that the three attributes of file1 and file2 and file3 are always:
filePath: which is always null;
path: "/documents/19/21704/liferay-portlet-development.pdf"
prefixLength: 1
Since I am also using Liferay I also tried their utility.
long compId = article.getCompanyId();
long contentLength = DLStoreUtil.getFileSize(compId, CompanyConstants.SYSTEM, s);
I also should notice that in my .xhtml view I can access the file with:
<a target="_blank"
href="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc">
file2.pdf
</a>
Pdf opens in a new window. So it is stored on my server.
What am I doing wrong here? That I cant get the file size from bean?
Any answer would be greatly appreciated.
What am I doing wrong here?
In Java, you can use the File.length() method to get the file size in bytes.
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
}
System.out.println("bytes : " + bytes);
The problem is that your "relative" path is expressed as an absolute path (begining with "/", which is read as FS root).
A relative file path should look like:
documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
./documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
Or, you could get your application root folder File and compose the absolute path:
File rootFolder =new File("path to your app root folder");
File myfile=new File(rootFolder, "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc");