How can I read a path from .txt in java - java

I have a txt file. This contains a directory (H: /). I want to read this directory. There are also a few csv files in the directory. I would like to see only the csv-files. My Java code contains everything relevant, I think. Now he does not find the text file. The text file is located in the project folder in Eclipse (so I used a relative path)
Where is my mistake?
EDIT: I make a common example of my problem
public class AllFiles {
public static void main(String[]args) throws IOException
{
File dir = new File("C:/Users/Example/Main/Test.txt");
getAllFiles(dir);
} private static void getAllFiles(File dir) throws IOException {
// Read from the file
BufferedReader br = new BufferedReader(new FileReader(dir));
String path = br.readLine();
br.close();
File[] fileArray = new File (line).listFiles(new FilenameFilter() {
//only data with .csv were shown
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
for(File f : fileArray){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
}

You never assign the content of the file to the variable line.
Change String line;
br.readLine(); to String line = br.readLine();
The next error is that you are try to list files from ".../Users/example/Test.txt". Whyt you want to try is:
File[] fileArray = new File(line).listFiles(...

Related

File directory error in JAR deployment

I'm trying to get the names of all the files in a folder "clock" which is inside the working directory "src".
The snippet below works fine if I run it but when I build the JAR file and run that I get a null error.
try {
File directory = new File("src/clock/");
File[] files = directory.listFiles();
for (File f: files) {
text.appendText(f.getName() + " ");
}
} catch (Exception e) {
text.appendText(e.getMessage() + " ");
}
File structure:
Update: (I'm using the ResourceAsStream now but same problem runs fine, deployed JAR doesn't work)
public void setImage() {
List<String>fn;
try {
fn = getResourceFiles("/clock/graphics/backgrounds/");
for (String s: fn) {
text.appendText(s);
}
} catch (Exception e) {
label.setText(e.getMessage());
}
}
private List<String>getResourceFiles(String path) throws IOException {
List<String> filenames = new ArrayList<>();
try (
InputStream in = getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader( in ))) {
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(resource);
}
}
return filenames;
}
private InputStream getResourceAsStream(String resource) {
final InputStream in = getContextClassLoader().getResourceAsStream(resource);
return in == null ? getClass().getResourceAsStream(resource) : in ;
}
private ClassLoader getContextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
That's because File searches in the
/path/to/your/application.jar
which File cant unzip to find the files in the specified path. It considers application.jar as a folder name and tries to read it.
Instead use
ClassLoader classLoader = YourClassName.class.getClassLoader();
InputStream sam = classLoader.getResourceAsStream(fileName);
to read the file from resources folder of the project when you want your jar to read a file.

Accessing an external file

I'm looking to reaccess a file created in android studio. I found the following code snippet on stack exchange
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
File file = new File(dir, "myData.txt");
From my understanding this creates a file called "myData.txt" in the download folder. What im looking to do is pass "file" into a function in another method like so
public void onLocationChanged(Location location) {
ArrayList<Location> list = new ArrayList<>();
list.add(location);
GPX.writePath(file,"hello",list);
}
How do I go about creating a file variable that acesses the txt file without actually creating a new file?
File root = android.os.Environment.getExternalStorageDirectory();
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File(root.getAbsolutePath() + "/download");
File file = new File(dir, "myData.txt");
Actually it does not create a physical file. It just creates an object in memory (referenced by file).
You can then use the reference in your method to write to a physical file, like so:
public void onLocationChanged(File location) throws IOException {
ArrayList<File> list = new ArrayList<>();
list.add(location);
writeToFile("Text", location);
}
private static void writeToFile(String text, File file)
throws IOException {
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(text);
}
}
Update 2
If you want to use the reference in your method, you can pass the file reference to your method which should have some code to write the text into the actual file:
GPX.writePath(file,"hello",list);
...
public static void writePath(File file, String n, List<Location> points) throws IOException {
...
try(BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(n);
}
}

get all absolute file path of pdf files in java

I need to get all the absolute file path of the files with extension .pdf. I am using the code mentioned below, but I'm able to only get the absolute file path of only one file.
How can I modify the code to get all the absolute file paths ?
public class FindFiles {
String absoluteFilePath = "";
String fileName;
public String PdfFiles(String parentDirectory, String fileExtension) {
FileFilter fileFilter = new FileFilter(fileExtension);
File parentDir = new File(parentDirectory);
// Put the names of all files ending with .pdf in a String array
String[] listOfTextFiles = parentDir.list(fileFilter);
if (listOfTextFiles.length == 0) {
System.out.println("There are no files in this direcotry!");
}
for (String file : listOfTextFiles) {
//construct the absolute file paths...
absoluteFilePath = new StringBuffer(parentDirectory).append(File.separator).append(file).toString();
fileName = file.toString();
}
return absoluteFilePath;
}
public static void main(String args[]) {
FindFiles f = new FindFiles();
f.PdfFiles("", "");
}
}
you are overrding absoluteFilePath every time in the loop;
try with
absoluteFilePath += new StringBuffer(parentDirectory).append(File.separator).append(file).toString();
Don't be bothered, use java.nio.file:
final Path dir = Paths.get(baseDir).toAbsolutePath();
final String filter = "*." + extension;
final List<Path> ret = new ArrayList<>();
try (
final DirectoryStream<Path> dirstream
= Files.newDirectoryStream(dir, filter);
) {
for (final Path entry: dirstream)
ret.add(entry);
}
return ret;
If you use Java 8, it's even more simple.
A more efficient solution for your problem can be given using classes in java.nio package.
E.g. For checking whether a file is a pdf file or not, use Files.probeContentType(Path path).
Instead of writing loops to visit all directories and files inside these directories, use Files.walkFileTree(Path start, FileVisitor<? super Path> visitor)
Solution for your problem using these classes are
public class FindPdfFiles {
public static void main(String[] args) throws IOException{
final Path path = Paths.get("C:\\SearchDirectoryForPDF");
Files.walkFileTree(path, new FindPdfFilesFilter());
}
}
class FindPdfFilesFilter extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path path, BasicFileAttributes arg1)
throws IOException {
final String mimeTypeOfFile = Files.probeContentType(path);
if(mimeTypeOfFile != null && !mimeTypeOfFile.isEmpty() && mimeTypeOfFile.toLowerCase().contains("pdf")) {
System.out.println(path.toString());
}
return FileVisitResult.CONTINUE;
}
}

How to know if an agument is a directory or file in Java

I am trying to pass an argument to a method . The argument can be a file or a direcotry.
public class ReadCsv {
String line = null;
BufferedReader br ;
public void readCsv(String arg) throws Exception{
File file = new File(arg);
if(file.isDirectory()){
for(File dir : file.listFiles()){
System.out.println(file.getName());
reader(dir);
}
}
else{
reader(file);
}
}
public void reader(File file) throws Exception {
br = new BufferedReader(new FileReader(file));
while((line=br.readLine())!=null){
//Code
}
}
But the code is not working as I want to. When I pass an argument arg , I have to determine whether it is a file or a directory and work according to it . Can anyone please help me how to determine a file or a directory .This code of mine runs the loop 4 times if arg is a directory.
Your code looks fine, looks like you're just outputting the directory (which you have named 'file') instead of the file, which you have named 'dir'.
for(File dir : file.listFiles()) {
System.out.println(dir.getName()); //you were outputting file.getName()
}
File has isDirectory() and isFile() methods you can use to check the type.
See File official documentation. There are methods such as:
isFile();
isDirectory();
Try It ..
It print all Directories and file name .
IF Nested Directories :
public class ReadCsv {
String line = null;
BufferedReader br ;
public void readCsv(String arg) throws Exception{
File file = new File(arg);
checkIsDir(file );
}
public void checkIsDir(File file) throws Exception {
if(file.isDirectory()){
System.out.println("Directory : "file.getName());
for(File dir : file.listFiles()){
checkIsDir(dir);
}
}
else{
System.out.println("File : "file.getName());
reader(file);
}
}
public void reader(File file) throws Exception {
br = new BufferedReader(new FileReader(file));
while((line=br.readLine())!=null){
//Code
}
}

How to copy file from directory to another Directory in Java

I am using JDK 6.
I have 2 folders names are Folder1 and Folder2.
Folder1 have the following files
TherMap.txt
TherMap1.txt
TherMap2.txt
every time Folder2 have only one file with name as TherMap.txt.
What I want,
copy any file from folder1 and pasted in Folder2 with name as TherMap.txt.If already TherMap.txt exists in Folder2, then delete and paste it.
for I wrote the following code.but it's not working
public void FileMoving(String sourceFilePath, String destinationPath, String fileName) throws IOException {
File destinationPathObject = new File(destinationPath);
File sourceFilePathObject = new File(sourceFilePath);
if ((destinationPathObject.isDirectory()) && (sourceFilePathObject.isFile()))
//both source and destination paths are available
{
//creating object for File class
File statusFileNameObject = new File(destinationPath + "/" + fileName);
if (statusFileNameObject.isFile())
//Already file is exists in Destination path
{
//deleted File
statusFileNameObject.delete();
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
//File is not exists in Destination path.
{
//paste file from source to Destination path with fileName as value of fileName argument
FileUtils.copyFile(sourceFilePathObject, statusFileNameObject);
}
}
}
I call the above function in main()
//ExternalFileExecutionsObject is class object
ExternalFileExecutionsObject.FileMoving(
"C:/Documents and Settings/mahesh/Desktop/InputFiles/TMapInput1.txt",
"C:/Documents and Settings/mahesh/Desktop/Rods",
"TMapInput.txt");
While I am using FileUtils function, it showing error so I click on error, automatically new package was generated with the following code.
package org.apache.commons.io;
import java.io.File;
public class FileUtils {
public static void copyFile(File sourceFilePathObject,
File statusFileNameObject) {
// TODO Auto-generated method stub
}
}
my code not showing any errors,even it's not working.
How can I fix this.
Thanks
Use Apache Commons FileUtils
FileUtils.copyDirectory(source, desc);
Your code isn't working because in order to use the ApacheCommons solution you will have to download the ApacheCommons library found here:
http://commons.apache.org/
and add a reference to it.
Since you are using JRE 6 you can't use all the NIO file utilities, and despite everyone loving Apache Commons as a quick way to answer forum posts, you may not like the idea of having to add that utility on just to get one function. You can also use this code that uses a transferFrom method without using ApacheCommons.
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream fIn = null;
FileOutputStream fOut = null;
FileChannel source = null;
FileChannel destination = null;
try {
fIn = new FileInputStream(sourceFile);
source = fIn.getChannel();
fOut = new FileOutputStream(destFile);
destination = fOut.getChannel();
long transfered = 0;
long bytes = source.size();
while (transfered < bytes) {
transfered += destination.transferFrom(source, 0, source.size());
destination.position(transfered);
}
} finally {
if (source != null) {
source.close();
} else if (fIn != null) {
fIn.close();
}
if (destination != null) {
destination.close();
} else if (fOut != null) {
fOut.close();
}
}
}
When you upgrade to 7, you will be able to do the following
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
reference:
https://gist.github.com/mrenouf/889747
Standard concise way to copy a file in Java?

Categories

Resources