a file addition by an incomplete (file) name [duplicate] - java

This question already has answers here:
How to check a file if exists with wildcard in Java?
(7 answers)
Closed 6 years ago.
I have a method:
public void setup () {
File file = new File(74761_control_*.xml)
//some code
}
Where * - variable part. Not known in advance how it will exactly be called a file. The program is required to load an xml file with the same name. Is there an elegant way to do this with a standard Java SE API?

The java.nio package has some convencience methods to iterate over directories using a file name pattern:
Path dir = Paths.get("c:\\temp");
Iterator<Path> iterator = Files.newDirectoryStream(dir,
"74761_control_*.xml").iterator();
Now, iterator "holds" all paths that fit to the glob pattern above.
The rest is iterator/file handling:
if (!iterator.hasNext()) {
// file not found
} else {
Path path = iterator.next();
// process file, e.g. read all data
Files.readAllBytes(path);
// or open a reader
try (BufferedReader reader = Files.newBufferedReader(path)) {
// process reader
}
if (iterator.hasNext()) {
// more than one file found
}
}

Related

Replace file with specific name java [duplicate]

This question already has answers here:
Copy file in Java and replace existing target
(4 answers)
Closed 6 years ago.
I make a java code that copy paste a file from a source to a destination.
My problem now that in every run a new file is pasted in the destination with numerical name. What I want is, to paste that file in the destination with specific name. And on running one more time a new file is created and replaced by the older. In order to get only one file.
I have used the following code:
String b = System.getProperty("user.home");
String src = b + "\\Desktop\\Nouveau dossier\\History";
String des = b + "\\Desktop\\Nouveau dossier2";
File from = new File(src);
File to = new File(des);
System.out.println("tt");
try {
if (file.exists()) {
FileUtils.copyFileToDirectory(file, to);
long size = from.length();
System.out.println("rr" + size);
} else {
System.out.println("No file");
}
}
first the file variable is not defined anywhere so you are calling function exists() on a null object.
Here's the code that might work for you (I replaced references to file variable with from which appears to be your intent):
try {
if (from.exists()) {
FileUtils.copyFileToDirectory(from, to);
long size = from.length();
System.out.println("rr" + size);
} else {
System.out.println("No file");
}
}

Loading file from resource gives a wrong path [duplicate]

This question already has answers here:
How to get a path to a resource in a Java JAR file
(17 answers)
Closed 7 years ago.
I have a propeties file with a path to a file inside my jar
logo.cgp=images/cgp-logo.jpg
This file already exists:
I want to load this file within my project so I do this:
String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg"
File file = new File(getClass().getClassLoader().getResource(property).getFile());
But then when I do file.exists() I get false. When I check file.getAbsolutePath() it leads to C:\\images\\cgp-logo.jpg
What am I doing wrong?
Well a file inside a jar is simply not a regular file. It is a resource that can be loaded by a ClassLoader and read as a stream but not a file.
According to the Javadocs, getClass().getClassLoader().getResource(property) returns an URL and getFile() on an URL says :
Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the concatenation of the value of getQuery(), if any. If there is no query portion, this method and getPath() will return identical results.
So for a jar resource it is the same as getPath() that returns :
the path part of this URL, or an empty string if one does not exist
So here you get back /images/cgp-logo.jpg relative to the classpath that does not correspond to a real file on your file system. That also explains the return value of file.getAbsolutePath()
The correct way to get access to a resource is:
InputStream istream = getClass().getClassLoader().getResourceAsStream(property)
You can use the JarFile class like this:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}

Reading a TXT file in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I keep getting a java.lang.NullPointerException when trying to open a txt file in eclipse. Basically, this is a main menu, and when you click the "Rules" button, the rules text file should open. Currently, the txt file is located in a package called "Resources" (which is where all of the other img files I've used in making the game are). Here's the code:
private List<String> readFile(String filename)
{
List<String> records = new ArrayList<String>();
try
{
BufferedReader buff = new BufferedReader(new InputStreamReader(
Configuration.class.getResourceAsStream(filename)));
String line;
while ((line = buff.readLine()) != null)
{
records.add(line);
}
buff.close();
return records;
}
catch (Exception e)
{
System.err.format("Exception occurred trying to read '%s'.", filename);
e.printStackTrace();
return null;
}
}
//action performed
public void actionPerformed(ActionEvent ae) {
JButton b = (JButton)ae.getSource();
if( b.equals(newGameButton) )
{
flag = true;
controller.startGame();
buttonPressed = "newGameBtn";
}
if(b.equals(quitButton))
{
System.exit(0);
}
if(b.equals(ruleButton)){
readFile("../resource/riskRules.txt");
}
}
Appreciate the help!
If "Resources" it's marked as resource in Eclipse. The txt file should be copied to your class path when you build.
As per what I can guess from your code you should be doing something like
Configuration.class.getResourceAsStream("riskRules.txt")
Since your file will be at the root level of your class path.
If for example the file is withing a dir called "text" in your resources you would use something like
Configuration.class.getResourceAsStream("text/riskRules.txt")
There needs to be some level of rudimentary error checking on the result returned from getResourceAsStream before you attempt to use it. Is there a reason you're using getResourceAsStream instead of getResource? If the file exists on disk (I see from your OP that it's because it's in a package, and may not physically exist on the disk), then you can just use that to return the path to it, and create a file object from it.
String path = "/path/to/resource"; // note the leading '/' means "search from root of classpath"
URL fileUrl = getClass().getResource(path);
if (fileUrl != null ) {
File f = new File(fileUrl.toURI());
BufferedReader = new BufferedReader(new FileReader(f));
// do stuff here...
}
else {
// file not found...
}
If you need to pull the file out of the JAR archive, then you can do this:
String path = "/path/to/resource"; // note the leading '/' means "search from root of classpath"
InputStream is = getClass().getResourceAsStream(path);
if (is != null ) {
BufferedReader = new BufferedReader(new InputStreamReader(is));
// do stuff here...
}
else {
// file not found...
}
In the event your resource is not found, you will avoid the NPE and you can properly account for the fact that it's missing.
Note that if you do have your resources in a package (jar), then you cannot use a path to locate it that uses "..", since there is no "relative path" in a jar archive, it's not actually a file on the filesystem.
Your "resources" are located by the relative path you specify in the getResource... method. A leading "/" means to look at the root of your classpath for locating the resource. No leading "/" means to look relative to the location of the class file that you're using to locate the resource.
If your file is in a location called "com.program.resources", and you're trying to locate it from a class called "com.program.someotherpackage.MyClass", then you'd use:
getClass().getResourceAsStream("/com/program/resources/<file.txt>");
to find it.
Here's my example illustrated:
<classpath root>
com
program
resources
file.txt
img.png
someotherpackage
MyClass.class
Generally, it's common practice to leave resources outside your package structure, to avoid confusion when locating them later. Most IDE's have a way to mark your directories as resources, so when the program is compiled, they will be copied to the proper location in the classpath root, and can be found by any class asking for them.

How to loop through all the files in a folder (if the names of the files are unknown)? [duplicate]

This question already has answers here:
how to read directories in java
(4 answers)
list all files from directories and subdirectories in Java
(6 answers)
Closed 9 years ago.
There is a folder: C:\\Users\..myfolder
It contains .pdf files (or any other, say .csv). I cannot change the names of those files, and I do not know the number of those files. I need to loop all of the files one by one.
How can I do this?
(I know how to do this if I knew the names)
Just use File.listFiles
final File file = new File("whatever");
for(final File child : file.listFiles()) {
//do stuff
}
You can use the FileNameExtensionFilter to filter your files too
final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "pdf", "csv"//, whatever other extensions you want);
final File file = new File("whatever");
for (final File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
//do stuff
}
}
Annoyingly FileNameExtensionFilter comes from the javax.swing package so cannot be used directly in the listFiles() api, it is still more convenient than implementing a file extension filter yourself.
File.listFiles() gives you an array of files in a folder. You can then split the filenames to get the extension and check if it is .pdf.
File[] files = new File("C:\\Users\..myfolder").listFiles();
for (File file : files) {
if (!file.isFile()) continue;
String[] bits = file.getName().split(".");
if (bits.length > 0 && bits[bits.length - 1].equalsIgnoreCase("pdf")) {
// Do stuff with the file
}
}
So you can have more options, try the Java 7 NIO way of doing this
public static void main(String[] args) throws Exception {
try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"))) {
for (Path path : files) {
System.out.println(path.toString());
}
}
}
You can also provide a filter for the paths in the form of a DirectoryStream.Filter implementation
public static void main(String[] args) throws Exception {
try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"),
new DirectoryStream.Filter<Path>() {
#Override
public boolean accept(Path entry) throws IOException {
return true; // or whatever you want
}
})
) {
for (Path path : files) {
System.out.println(path.toString());
}
}
}
Obviously you can extract the anonymous class to an actual class declaration.
Note that this solution cannot return null like the listFiles() solution.
For a recursive solution, check out the FileVisitor interface. For path matching, use the PathMatcher interface along with FileSystems and FileSystem. There are examples floating around Stackoverflow.
You can use Java.io.File.listFiles() method to get a list of all files and folders inside a folder.

Move all files from folder to other folder with java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying files from one directory to another in Java
How can I move all files from one folder to other folder with java?
I'm using this code:
import java.io.File;
public class Vlad {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// File (or directory) to be moved
File file = new File("C:\\Users\\i074924\\Desktop\\Test\\vlad.txt");
// Destination directory
File dir = new File("C:\\Users\\i074924\\Desktop\\Test2");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.print("not good");
}
}
}
but it is working only for one specific file.
thanks!!!
By using org.apache.commons.io.FileUtils class
moveDirectory(File srcDir, File destDir) we can move whole directory
If a File object points to a folder you can iterate over it's content
File dir1 = new File("C:\\Users\\i074924\\Desktop\\Test");
if(dir1.isDirectory()) {
File[] content = dir1.listFiles();
for(int i = 0; i < content.length; i++) {
//move content[i]
}
}
Since Java 1.7 there is java.nio.file.Files which offers operations to work with files and directories. Especially the move, copy and walkFileTree functions might be of interest to you.
You can rename the directory itself.
You can iterate over files in directory and rename them one-by-one. If directory can contain subdirectories you have to do this recursively.
you can use utility like Apache FileUtils that already does all this.

Categories