Im creating an app in android studio that grabs audio files and reads the metadata.
Uri uri = resultIntent.getData();
String[] split = uri.getPath().split("/");
String path = android.os.Environment.getExternalStorageDirectory().toString()
+"/"+ split[split.length-2]
+ "/" + split[split.length-1];
It works fine when I try to grab from my Downloads Folder but when I attempt to grab from my SD Card, my file has a random string appended infront of it.
/storage/emulated/0/document/1D09-2116:song.mp3
What could I do to remove it?
If that random string maintains the same format everytime then you could possibly use regex alongside the replaceAll() function.
String str;
String regex = ".*-\d+:";
str = str.replaceAll(regex, split[split.length-1]);
String path = android.os.Environment.getExternalStorageDirectory().toString()
+"/"+ split[split.length-2]
+ "/" + str;
Related
I want to split the following String
"C:\ATS\Script\SampleFiles\xml\books.xml"
to extract only name of the file (books.xml)
I tried using the split function but couldn't split \
if (file.isDirectory()) {
String fol = file.getCanonicalPath() ;
String foln = fol.split("C:\\ATS\\Script\\SampleFiles\\xml")[1];
System.out.println("directory:" + foln);
}
I want the output to extract only the file name
i.e books.xml
Use getFileName() method in Path
Path path = Paths.get("C:/ATS/Script/SampleFiles/xml/books.xml");
System.out.println(path.getFileName().toString());
Output
books.xml
Is this it?
String fol = ...
String split[];
split = fol.split("\\");
String foln = split[split.length-1];
You can do it simpler
File dir = new File("D:\\foo");
File file = new File("D:\\foo\\test.txt");
System.out.println("file.getName() = " + file.getName()); // test.txt
System.out.println("dir.getName() = " + dir.getName()); // foo
This is a correction of my previous question Put brackets around filename for Excel formula
My project is based on Apache POI.I'm trying to use a formula on a cell.
My formula is as follows.
sheet7.createRow(0).createCell(0).setCellFormula("+'C:\\Users\\Desktop\\[Test.xlsx]Average_Graph'!A2");
Im using a JFileChooser, which allows users to select the file. Therefore the filepath will be changed every time the program is used.
From the JFileChooser, I'm getting a filepath as follows.
String filepath= "C:\\Users\\Desktop\\Sheet.xlsx"`
In order to work the formula correctly, the filepath should be in following format.
"C:\\Users\\Desktop\\[Sheet.xlsx]"
How Can I Change the string which I'm getting from the JFileCHooser to run the formula correctly?
In previous question, I mistakenly typed C:\Users\Desktop[Sheet.xlsx] instead of C:\Users\Desktop\[Sheet.xlsx]
The answers gave me the output which i've mentioned. But I need the Output as C:\Users\Desktop\[Sheet.xlsx]
Please help.
If you want to solve this by directly altering the file path, you may use String#replaceAll:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.replaceAll("(?<=\\\\)([^\\\\]+)$", "[$1]");
System.out.println(filepath);
C:\Users\Desktop\[Sheet.xlsx]
Demo
File names won't have \backslashes in them, so we can assume that our filename begins after the last backslash and ends at the end of the string.
We can use this:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
String dir = filepath.substring(0, filepath.lastIndexOf("\\"+1));
String filename = filepath.substring(filepath.lastIndexOf("\\"+1));
filepath = dir + "[" + filename + "]";
Or a shorter version:
String filepath = "C:\\Users\\Desktop\\Sheet.xlsx";
filepath = filepath.substring(0, filepath.lastIndexOf("\\"+1)) +
"[" + filepath.substring(filepath.lastIndexOf("\\"+1)) + "]";
This question already has answers here:
How to generate a random alpha-numeric string
(46 answers)
Closed 5 years ago.
I am uploading a file to a folder , i had given the file name as "1.jpg" , so when i am uploading a new file it will overwrite the existing one,
So How i can give a random file name to the file which i am uploading
MY UPLOAD CODE IS HERE
#RequestMapping(value = "/event/uploadFile",headers=("content-type=multipart/*"), method = RequestMethod.POST,consumes ={"application/x-www-form-urlencoded"})
//String quote_upload=C:\fakepath\images.jpg
public #ResponseBody
String uploadFileHandler(
#RequestParam MultipartFile file) {
System.out.println("Creating the directory to store file");
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator+"1.jpg");
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("************Server File Location="
+ serverFile.getAbsolutePath());
//return "You successfully uploaded file=" + name;
} catch (Exception e) {
System.out.println("************failes"+ e.getMessage());
//return "You failed to upload " + name + " => " + e.getMessage();
}
//return "You failed to upload " + name
//+ " because the file was empty.";
}
System.out.println("hello");
return "hello";
}
If you do not expect the names to have any sensible order, I would probably go with UUID. Something like this should do it:
String filename = UUID.randomUUID().toString();
If you're worried about uniqueness of the UUID, have a look at this thread. In short, you are extremely unlikely to ever get two ids that are the same.
Generate a Random Name for your newly uploaded file
String fileName = UUID.randomUUID().toString()+YOUR_FILE_EXTENSION;
Check if File exist in the directory you are uploading
if(serverFile.exists())
If File Exist start again from step 1 until you get a file name which is not present in the server.
Note: This is not the optimal solution but will fulfill your requirement.
You can use
Calendar.getInstance().getTimeInMillis();
It will return the time in milliseconds.
If you are not sure about this append some random number to it.
You may use:
File.createTempFile(String prefix, String suffix, File directory)
As the JavaDoc states:
Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. If this method returns successfully then it is guaranteed that:
The file denoted by the returned abstract pathname did not exist before this method was invoked, and
Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.
You can simply get a random large integer and give your file that name, like so:
String fileExtension = ".jpg";
String fileName = Integer.toString(new Random().nextInt(1000000000)) + fileExtension;
assuming that we have a folder with path:
path="C:\\Users\\me\\Desktop\\here"
also, consider a File[] named readFrom has different files. as an example, consider following path which refering to a file:
C:\\Users\\me\\Desktop\\files\\1\\sample.txt"
my question is, how can i have a string with following value:
String writeHere= "C:\\Users\\me\\Desktop\\here\\files\\1\\sample.txt"
EDIT
I should have mentioned that this path is unknown, we need first to read a file and get its path then write it into another folder, so for the path of writing I need writeHere as input. in conclusion , the answer should contains the way to get the path from the file too.
String s1="C:\\Users\\me\\Desktop\\here";
String s2="C:\\Users\\me\\Desktop\\files\\1\\sample.txt";
String s3=s2.substring(s2.indexOf("\\files"));
System.out.println(s1+s3);
OUTPUT
C:\Users\me\Desktop\here\files\1\sample.txt
To get Absolute Path of file
File f=new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
System.out.println(f.getAbsolutePath());
Split the into arrays and merge the path with split-ted string
String path="C:\\Users\\me\\Desktop\\here";
String [] splt = yourPath.split("\\");
finalPath = path + "\\" + splt[3] + "\\" + splt[4] + "\\" + splt[5];
yourPath is the path refering to a file
Changing the folder's path
File afile =new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
afile.renameTo(new File(finalPath))
If you just need the String and do not need to read the file, use string concatenation with is just str1 + str2. If you need the File object create a base File object on the initial path and then two new File objects from that:
File path = new File("C:\\Users\\me\\Desktop\\here");
String[] files = { "files\\1\\sample.txt", "files\\3\\this.avi" };
for (filename in files) {
File f = new File(path, filename);
...
}
Oh, I think I see better what you want to do. You want to "reparent" the files:
// Note:
// newParent I assume would be a parameter, not hardcoded
// If so, there is no hardcoding of the platform specific path delimiter
// the value, start, is also assumed to be a parameter
File newParent = new File("C:\\Users\\me\\Desktop\\here");
File[] readFrom = ...;
for (File f in readFrom) {
String[] parts = f.list();
String[] needed = Arrays.copyOfRange(parts, start, parts.length);
File newFile = new File(newParent);
for (String part in needed) {
newFile = new File(newFile, part);
}
...
}
I think you could do something like:
String name = "Rafael";
String lastname = " Nunes";
String fullname = name + lastname;
Here you can see the string concatenation working, and you can often visit the Java documentation.
I am writing a program that has multiple users, and I want each user to be able to save a file with a filename they choose, but, also append their username or a related key to the file name to help with searching later on. How can I adjust this code to do so?
For example, the user "bob" wants to save a file as "aFile.html". The file I want to actually save would be "aFile_bob.html"
String user = "bob";
// select a file to save output
JFileChooser JfileChooser = new JFileChooser(new File(defaultDirectory));
JfileChooser.setSelectedFile(new File("TestFile.html"));
int i = JfileChooser.showSaveDialog(null);
if (i != JFileChooser.APPROVE_OPTION) return;
File saveFile = JfileChooser.getSelectedFile();
// somehow append "user" to saveFile name here?
FileOutputStream fop = new FileOutputStream(saveFile);
Use the renameTo method, like this:
int lastDot = saveFile.getName().lastIndexOf('.');
String name = saveFile.getName();
String ext = ""; // Might not have a file extension
if(lastDot > 0) { // At least one dot
// Take substring of the last occurrence
ext = saveFile.getName().substring(lastDot);
name = name.substring(0, lastDot);
}
saveFile.renameTo(new File(defaultDirectory + "/" + name + "_" + user + ext));
Using this method, you don't need the FileOutputStream.