This question already has answers here:
Parsing File name of a doc file of java
(2 answers)
Closed 9 years ago.
I am trying to parse multiple file names(doc file)in java.
How should I go about doing this?
I asked a previous post and got a answer on how to parse a file name in java.
Thanks for that.
So in a directory, I have multiple files(with different names). For instance, there are files
AA_2322_1
AA_2342_1
BB_2324_1
CC_2342_1
I want to parse the middle 4 digit-5digit numbers only.
Suppose you have a directory C:\XYZ with the files you listed above, with .doc extensions on them. Taking advantage of a FileFilter, you can get a list of the numbers you are looking for with the following code:
File directory = new File("C:/XYZ");
final ArrayList<String> innerDigits = new ArrayList<String>();
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File pathname) {
if (!pathname.isFile() || !pathname.getName().endsWith("doc"))
return false;
// Extract whatever you need from the file object
String[] parts = pathname.getName().split("_");
innerDigits.add(parts[1]);
return true;
}
};
// No need to store the results, we extracted the info in the filter method
directory.listFiles(filter);
for (String data : innerDigits)
System.out.println(data);
Getting the filenames of all files in a folder - Use this question to get the name of all the files in the directory. Then use the String.split() function to parse the file names.
You can use split method
String[] parts = filename.split("_");
Now you need parts[1]
Related
This question already has answers here:
How to make FileFilter in Java?
(10 answers)
Closed 4 years ago.
I want my JFileChooser to only display directories and files that start with any variable, for example all files that start with jgg300...
I tried using FileFilter but it only works for files that have a file format like bat or exe, my files don't have a file format they are just files.
I tried using some solutions I found on google but they didn't work
Maybe I'm using FileFilter wrong but I can't get it to work.
edit:
I want to filter by the Start of the file not the end.
Create a new FilenameFilter like so
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
return fileName.startsWith("jgg300");
}
});
This question already has answers here:
How to split a path platform independent?
(6 answers)
How to get the path string from a java.nio.Path?
(2 answers)
Where to use resolve() and relativize() method of java.nio.file.Path class?
(5 answers)
Create a Path from String in Java7
(4 answers)
Recursively list files in Java
(30 answers)
Closed 4 years ago.
I'm currently working on a search output system that searches a directory for a specific phrase in a file, matches it, then outputs it to a log file. I have a problem snippet of code that looks like this:
int j = 0;
for(String currentMatch : lineMatch) {
String[] split = fileList.get(j).toString().split("\\\\");
match.write(split[3] + " : " + currentMatch + "\r\n");
match.flush();
j++;
}
With fileList being an arraylist of the file names with a matching result and filePath being an arraylist of the file path. I used the split[3] to return the name of the the forth folder in this directory that I'm interested in.
The output file then becomes a little funky. This directory in question has roughly 40 unique names, but the log ends up looking like this:
dir1 : matchingline
dir2 : matchingline
dir3 : matchingline
dir3 : matchingline
... (x543)
dir4 : matchingline
And so on. Directory 3 is only supposed to have 88 matching lines and ends up with an additional 455 lines that belong to other directories. Any idea on why this happens? Is it because I'm using an assignment in the middle of a PrintWriter, or am I missing something simple here?
Edit: Variables listed for clarity.
match = Printwriter object used to print to an output.
lineMatch = ArrayList() - contains the directory path of the current matched file
fileMatch = ArrayList() - contains the file name that was matched.
split[3] is used because the matched files are consistently found in the 4th directory in, ex. C:\User\Programs\Programname\
/r/n is used to keep formatting on windows.
This is a personal project, so I'm not too concerned with making it portable.
Edited to add the method used for initializing the arraylist.
public static void addFiles(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
try {
if(files.length == 0) {
emptyFilePath.add(dirPath);
}
else {
for (File currentFile : files) {
if(currentFile.isFile()) {
fileList.add(currentFile);
filePath.add(currentFile.getPath());
}
else if (currentFile.isDirectory()) {
addFiles(currentFile.getAbsolutePath());
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
And the code that generates lineMatch:
while(i < fileList.size()) {
File files = new File(filePath.get(i));
Scanner file = new Scanner(files);
try {
while(file.hasNextLine()) {
String currentLine = file.nextLine();
if(currentLine.contains(searchString)) {
lineMatch.add(currentLine);
}
}
}finally {
file.close();
}
i++;
}
There are a number of things that are suspicious about your code.
Are LineMatch and FileList variables? If so, then you should write them like variables, that is, lineMatch and fileList (lowerCamelCase). Doing otherwise confuses readers and syntax highlighters alike.
You use split[3], that looks suspicious.
If you are using split("\\\\") in order to get the directory path parts, beware that your code is non-portable, it will work on Windows only. If you want to split a path into its parts, it's better to use the API.
In order to understand the problem, it would be useful to see how LineMatch and FileList are generated, without that, it's not possible to understand what's going wrong in your code.
If match is a PrintWriter or PrintStream, you should use println() or format("...%n") instead of write(... + "\r\n"). Again, because your code is not portable. On Unix, line endings are \n only, not \r\n.
The actual problem is with your program logic. Your variable lineMatch contains the hits of all files found. Because you don't generate a separate lineMatch for each file, but just a single one for all files. At least that's how it looks like from the code that you've posted so far.
It looks like what you want to program is a simple version of grep (or, on DOS, find). Part of your logic is correct, for example, how you use recursion to descend in to the directory tree. Instead of collecting all matches and then printing, find and print the matches while you're traversing the directory tree.
In general, you will end up with less errors if you avoid global variables. You ran into a problem in the first place because your variables LineMatch and FileList are global variables. Avoid global variables, avoid reusing variables, and also avoid variable re-assignment.
I'm working on a Java code to copy the data from one csv file into another csv file .
The requirement is that files (multiple files) that are uploaded in a particular path has to be copied one at a time into another csv file(say tag.csv) in a different location.Later tag.csv will be picked up by a shell script and connect to Oracle DB to run a stored procedure .All of this is done repeatedly until all the uploaded files is processed and shell script is triggered for each file separately.
Now I'm in stuck in copying the csv data .
I have tried using buffered reader,filewriter etc. but i'm unable to copy the data to tag.csv,but I could just read them .
Since Im new to java im finding it hard to understand where im going wrong.
Help is much appreciated.
You can simply use the Java 7 NIO2:Eg:
If you want to copy a file from one location to another, simply call:
Files.copy(fromPath, toPath);
If you want to move:
Files.move(fromPath, toPath);
With Java 7 features, you don't need to write hard code for files handling. Hope it help.
Java 7 NIO2 Tutorial Link
Edited:
But your requirement is not file copy but you want to write uploaded file contents to existing file, you can also simply use the Java 7 NIO2 features.
Eg:
private static void writeFileAsAppend() throws IOException {
List<String> lines = readFileAsSequencesOfLines();
Path path = getWriteFilePath();
Files.write(path, lines, StandardOpenOption.APPEND);
}
private static List<String> readFileAsSequencesOfLines() throws IOException {
Path path = getReadFilePath();
List<String> lines = Files.readAllLines(path);
return lines;
}
private static Path getReadFilePath() {
Path path = Paths
.get(".\\ReadMe.csv");
return path.normalize();
}
private static Path getWriteFilePath() {
Path path = Paths
.get(".\\WriteMe.csv");
return path;
}
This question already has answers here:
FileNotFoundException, the file exists Java [closed]
(2 answers)
Closed 7 years ago.
Hello I have this in my code
File file = new File("words.txt");
Scanner scanFile = new Scanner(new FileReader(file));
ArrayList<String> words = new ArrayList<String>();
String theWord;
while (scanFile.hasNext()){
theWord = scanFile.next();
words.add(theWord);
}
But for some reason I am getting a
java.io.FileNotFoundException
I have the words.txt file in the same folder as all of my .java files
What am I doing wrong? Thanks!
Tip: add this line to your code...
System.out.println(file.getAbsolutePath());
Then compare that path with where your file actually is. The problem should be immediately obvious.
The file should reside in the directory from which you execute the application, i.e. the working directory.
Generally it's a good idea to package data files with your code, but then using java.io.File to read them is a problem, as it's hard to find them. The solution is to use the getResource() methods in java.lang.ClassLoader to open a stream to a file. That way the ClassLoader looks for your files in the location where your code is stored, wherever that may be.
try:
URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());
You haven't specified an absolute path. The path would therefore be treated as a path, relative to the current working directory of the process. Usually this is the directory from where you've launched the Main-Class.
If you're unsure about the location of the working directory, you can print it out using the following snippet:
System.out.println(System.getProperty("user.dir"));
Fixing the problem will require adding the necessary directories in the original path, to locate the file.
This question already has answers here:
Closed 12 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
Best way to iterate through a directory in java?
I want to process each file in a certain directory using Java.
What is the easiest (and most common) way of doing this?
If you have the directory name in myDirectoryPath,
import java.io.File;
...
File dir = new File(myDirectoryPath);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
// Do something with child
}
} else {
// Handle the case where dir is not really a directory.
// Checking dir.isDirectory() above would not be sufficient
// to avoid race conditions with another process that deletes
// directories.
}
I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles method and you can process each file.
You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi
Here's an example:
Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
while(it.hasNext()){
System.out.println(((File) it.next()).getName());
}
You can change null and put a list of extentions if you wanna filter. Example: {".xml",".java"}
Here is an example that lists all the files on my desktop. you should change the path variable to your path.
Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.
public static void main(String[] args) {
File path = new File("c:/documents and settings/Zachary/desktop");
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
}
}
}
Use java.io.File.listFiles
Or If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles