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");
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
I am trying to write a bitmap to any of the usual internal folders like 'Pictures, Documents, Download' etc. Below is the file creation I am doing
String root = Environment.getRootDirectory().toString();
File myDir = new File(root + File.separator + Environment.DIRECTORY_PICTURES);
String Filename = "pic.png";
File fl = new File(myDir + File.separator + Filename);
FileOutputStream out = new FileOutputStream(fl);
At the last line, it throws an exception which says 'No such File/Directory'.
If I check fl.canWrite(), it says false!, i.e. fl is not writable.
I even tried to give 'Unrestricted Access' in my testing mobile for this App.
What could be the problem?
What kind of additional things I need to do?
Edit: When I toast, myDir is shown as /system/Pictures. When I go to File Manager in phone, under my 'Phone storage', 'Pictures' folder is there. That's a usual folder in Android right ?
you should use
\\...
File myDir = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
\\...
then do a check to confirm directory exist and then proceed to write your file.
I'm trying to get the directory path to a file. The issue I am having is getting the last \ or / of the directory. As this code is supposed to work on all operating systems, I can't seem to find any solution for this. Any help is appreciated.
My code so far:
System.out.print("Enter dir: ");
String path = kb.nextLine();
File pathes = new File(path);
String path2 = pathes.getParent();
path = path.substring(0, path.lastIndexOf("\\")+1);
System.out.println("PATH: " + path);
System.out.println("PATH2: "+path2);
My output is:
PATH: C:\Users\User\Desktop\test\
PATH2: C:\Users\User\Desktop\test
This is just test code and not the real code I'm working on.
EDIT
What I'm trying to get is
C:\Users\User\Desktop\test\
from
C:\Users\User\Desktop\test\test.txt
To get the absolute path to the parent directory you can do:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt");
String path = f.getParentFile().getAbsolutePath();
System.out.println(path);
Output:
C:\Users\User\Desktop\test
If you really want the trailing slash, then you can just append File.separator:
File f = new File("C:\\Users\\User\\Desktop\\test\\test.txt ");
String path = f.getParentFile().getAbsolutePath() + File.separator;
System.out.println(path);
Output:
C:\Users\User\Desktop\test\
In Java, I have a File object representing a folder:
String folderName = "/home/vektor/folder";
File folder = new File(folderName);
Now I want to create another File representing a file in this folder. I want to avoid doing a string concatenation like this:
String fileName = "test.txt";
File file = new File(folderName + "/" + fileName);
Because if I go deeper in creating this structure, I will come up with something like this:
File deepFile = new File(folderName + "/" + anotherFolderName + ... + "/" + fileName);
I would instead like to do something like
File betterFile = folder.createUnder(fileName);
Or even:
File otherFile = SomeFileUtils.createFileInFolder(folder, fileName);
Do you know of such solution?
Note: It's quite OK to use "/" because Java will translate it to "\" for Windows, but it is not clean - I should use something like "file.separator" from System.getProperties().
Look at the Javadoc for File and you will see that the constructor takes a File object as parent.
Use the following form:
File deepFile = new File(folder, fileName);
I would use
String folderName =
String fileName =
File under = new File(folderName, fileName);
or
File folderFile =
String fileName =
File under = new File(folderFile, fileName);
simple as that ;)
I want to create a text file into that folder that I am creating here.
File dir = new File("crawl_html");
dir.mkdir();
String hash = MD5Util.md5Hex(url1.toString());
System.out.println("hash:-" + hash);
File file = new File(""+dir+"\""+hash+".txt");
But this code doesn't create the text file into that folder..Instead it makes the text file outside that folder..
One of java.io.File's constructors takes a parent directory. You can do this instead:
final File parentDir = new File("crawl_html");
parentDir.mkdir();
final String hash = "abc";
final String fileName = hash + ".txt";
final File file = new File(parentDir, fileName);
file.createNewFile(); // Creates file crawl_html/abc.txt
What you need is
File file = new File(dir, hash + ".txt");
The key here is the File(File parent, String child) constructor. It creates a file with the specified name under the provided parent directory (provided that directory exists, of course).
The line
new File(""+dir+"\""+hash+".txt");
makes a file named crawl_html"the_hash.txt, because \" inside a String literal is used to represent a double quote caracter, not a backslash. \\ must be used to represent a backslash.
Use the File constructor taking a File (directory) as the first argument, and a file name as a second argument:
new File(dir, hash + ".txt");
your path-delimiter seems off
try:
File file = new File ( "" + dir + "/" + hash + ".txt" );