Exporting a given directory and file list to a file using BufferedWriter on Java8 (Eclipse IDE). This is working fine.
Some files have special characters like "[", "]" or extensions such as ".zip" that I wish to strip out when saving my file. Tried .replaceALL but getting stuck with how to make this work. Any suggestions please?
public static void getDirectoryList() throws IOException
{
String path = "C:\\Users\\";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("DirectoryList.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getName());
BufferedWriter bw = new BufferedWriter(fw);
for (File f : listOfFiles) {
// .replaceALL wants to be cast. Is there an alternative to
// .replaceAll when listing out a file listing to file.
// Or, am I doing something silly....
f = f.replaceAll(".zip", "");
bw.write(f.getName());
bw.newLine();
}
bw.close();
}
Example of Current text file output:
[name1].doc <-trying to remove "[" and "]" when saving name to file.
filename.zip <-trying to remove ".zip" when saving name to file.
directoryname1
directoryname2
(Original file and directory names remain, only the results save to the file are being changed.)
Required text file output
name1.doc
filename
directoryname1
directoryname2
replaceAll isn't a method of File, it's a method of String.
for(File f : listOfFiles) {
String fileName = f.getName();
fileName = fileName.replaceAll("\\.zip", "");
fileName = fileName.replaceAll("\\[", "");
fileName = fileName.replaceAll("]", "");
bw.write(fileName);
bw.newLine();
}
Also notice that when I use replaceAll to remove '.zip' from the filename the . must be escaped. That's because the first parameter of replaceAll is a regex and dot . is a special character. The same for [.
There is a more compact way to do the same thing with a single regex
for(File f : new File("").listFiles()) {
String fileName = f.getName();
fileName = fileName.replaceAll("\\.zip|\\[|]", "");
bw.write(fileName);
bw.newLine();
}
Related
I'm saving an uploaded file as below:
UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
dir.mkdir();
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName());
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();
But my question is when upload once file same old file in folder D:/FileUpload. In above function it will delete old file. Example first time, i upload file : test.doc (old file). Then i upload another file with same name : test.doc (new file). At folder FileUpload will has one file is test.doc (new file). I want function will process similar in window OS is : new file will be test (2).doc. How can i process it ? And all cases : D:/FileUpload have many file : test.doc, test (1).doc, test (2).doc, test (a).doc,...... I think we just check with format ....(int).doc. That new file will be :
test (3).doc (ignore test(a).doc)
Maybe you're looking for something like this? I list the files in your directory, compare the names of each to the name of your file. If the names match, increment a count. Then, when you come to create your file, include the count in its name.
UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
dir.mkdir();
}
String [] files = dir.list();
int count = 0;
for(String file : files) {
if (file.startsWith(item.getFileName()) {
count++;
}
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName() + "(" + count + ")");
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();
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 have a directory in my jar called "lessons". Inside this directory there are x number of lesson text files. I want to loop through all these lessons read their data.
I of course know how to read a file with an exact path:
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/lesson1.lsn")));
try{
in.readLine();
}catch(IOException e){
e.printStackTrace();
}
But what I want is something more like this:
File f = new File(Main.class.getResource("lessons"));
String fnames[] = f.list();
for(String fname : fnames){
BufferedReader in = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream("lessons/" + fname)));
in.readLine();
}
File however doesn't take a URL in it's constructor, so that code doesn't work.
I will use junit.jar in my test as an example
String url = Test1.class.getResource("/org/junit").toString();
produces
jar:file:/D:/repository/junit/junit/4.11/junit-4.11.jar!/org/junit
lets extract jar path
String path = url.replaceAll("jar:file:/(.*)!.*", "$1");
it is
D:/repository/junit/junit/4.11/junit-4.11.jar
now we can open it as JarFile and read it
JarFile jarFile = new JarFile(path);
...
Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
I am trying to move a file from one directory to another using renameTo() in java, however renameTo doesnt work (doesnt rename and move the file). Basically, I want to delete the file in one first with same file name, then copy a file from anoter directory to the same location where I deleted the file originally, then copy the new one with same name.
//filePath = location of original file with file name appended. ex: C:\Dir\file.txt
//tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir
int pos = filePath.indexOf("C:\\Dir\\file.txt");
//Parse out only the path, so just C:\\Dir
String newFilePath = filePath.substring(0,pos-1);
//I want to delete the original file
File deletefile = new File(newFilePath,"file.txt");
if (deletefile.exists()) {
success = deletefile.delete();
}
//There is file already exists in the directory, but I am just appending .tmp at the end
File newFile = new File(tempPath + "file.txt" + ".tmp");
//Create original file again with same name.
File oldFile = new File(newFilePath, "file.txt");
success = oldFile.renameTo(newFile); // This doesnt work.
Can you tell me what I am doing wrong?
Thanks for your help.
You need to escape the backslashes in the string literal: "C:\\Dir\\file.txt". Or use File.separator to construct the path.
Additionally, ensure newFile's path is constructed properly:
File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp");
//^^^^^^^^^^^^^^^^
as the commments in the posted code (...ex: C:\AnotherDir) indicate that tempPath has no trailing slash character.
I have moved files to the destination directory and after moving deleted those moved files from source folder, in three ways, and at last am using the 3rd approach in my project.
1st approach:
File folder = new File("SourceDirectory_Path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName()));
}
System.out.println("SUCCESS");
2nd approach:
Path sourceDir = Paths.get("SourceDirectory_Path");
Path destinationDir = Paths.get("DestinationDerectory_Path");
try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){
for (Path path : directoryStream) {
File d1 = sourceDir.resolve(path.getFileName()).toFile();
File d2 = destinationDir.resolve(path.getFileName()).toFile();
File oldFile = path.toFile();
if(oldFile.renameTo(d2)){
System.out.println("Moved");
}else{
System.out.println("Not Moved");
}
}
}catch (Exception e) {
e.printStackTrace();
}
3rd approach:
Path sourceDirectory= Paths.get(SOURCE_FILE_PATH);
Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) {
for (Path path : directoryStream) {
Path dpath = destinationDirectory .resolve(path.getFileName());
Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}
Happy Coding !! :)