Accessing an external file - java

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);
}
}

Related

How to get a file without the extension in Java?

I'm saving images to my resources folder regardless of the extension, and I want to load them the same way. Example: I want to get the image named "foo" whether it is "foo.jpg" or "foo.png".
Right now I'm loading the image for each extension and returning it if it exists OR trying for the next extension if an exception is thrown like so:
StringBuilder relativePath = new StringBuilder().append("src/main/resources/static/images/").append("/")
.append(id).append("/").append(imageName);
File imageFile = null;
byte[] imageBytes = null;
try {
imageFile = new File(new StringBuilder(relativePath).append(".jpg").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
} catch (IOException e) {
}
if (imageBytes == null) {
imageFile = new File(relativePath.append(".png").toString());
imageBytes = Files.readAllBytes(imageFile.toPath());
}
I feel like it's not the best way to do that, is there a way to load an image by its name and regardless of the extension?
You need to check it the file exists
File foo = new File("foo.jpg");
if (!foo.exists) {
foo = new File("foo.png");
}
But if you really want to load without using the extension, then you could list the files in directory that match a given pattern.
File dir = new File("/path/to/images/dir/");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.matches("foo\\.(jpg|png)");
}
});
File foo = files[0];

How to move files from Parent directory to subdirectory in java?

I am able to copy the contents from one folder to Targetfolder including subfolders but also i need to copy only the files which are present in source directory to subdirectory.
Please find my below code:
private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
{
//Check if sourceFolder is a directory or file
//If sourceFolder is file; then copy the file directly to new location
if (sourceFolder.isDirectory())
{
//Verify if destinationFolder is already present; If not then create it
if (!destinationFolder.exists())
{
destinationFolder.mkdir();
System.out.println("Directory created :: " + destinationFolder);
}
//Get all files from source directory
String files[] = sourceFolder.list();
//Iterate over all files and copy them to destinationFolder one by one
for (String file : files)
{
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
//Recursive function call
copyFolder(srcFile, destFile);
}
}
else
{
//Copy the file content from one place to another
Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + destinationFolder);
}
}
}
I've added a new parameter to copyFolder. If set to false only the files are copied, not the folder:
public static void main(String[] args) throws IOException {
// Source directory which you want to copy to new location
File sourceFolder = new File("/workspace/files/");
// Target directory where files should be copied
File destinationFolder = new File("/Workspace/Out/");
// Call Copy function
copyFolder(sourceFolder, destinationFolder, false);
}
/**
* This function recursively copy all the sub folder and files from sourceFolder
* to destinationFolder
*/
private static void copyFolder(File sourceFolder, File destinationFolder, boolean subFolders) throws IOException {
// Check if sourceFolder is a directory or file
// If sourceFolder is file; then copy the file directly to new location
if (sourceFolder.isDirectory()) {
// Verify if destinationFolder is already present; If not then create it
if (!destinationFolder.exists()) {
destinationFolder.mkdir();
System.out.println("Directory created :: " + destinationFolder);
}
// Get all files from source directory
String files[] = sourceFolder.list();
// Iterate over all files and copy them to destinationFolder one by one
for (String file : files) {
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
// Recursive function call
if (subFolders) {
copyFolder(srcFile, destFile, subFolders);
}
}
} else {
// Copy the file content from one place to another
Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + destinationFolder);
}
}
You can use Files.walk to create a stream of Path instances, filter the files and copy them to the destination.
try(Stream<Path> pathStream = Files.walk(sourceFolder)) {
pathStream
.filter(path -> path.toFile().isFile())
.forEach(path -> {
Path destinationFile = Paths.get(destinationFolder.toPath().toString(),
path.getFileName().toString());
copyFile(path, destinationFile);
});
}
private static void copyFile(Path src, Path dst) {
try {
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}

How can I read a path from .txt in 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(...

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?

How to include an XML database into a jar file and access to it?

Currently, I can only make my app access to the XML database when the jar file and XML file in the same directory, and what I hope is that there is only one single jar file which includes the XML file. How can I do that?
private String getXmlPath() {
String url = "";
try {
String cp = "Data\\QuestionList.xml";
File f = new File(ClassLoader.getSystemResource("\\").toURI().getPath());
url += f.getPath() + "\\" + cp;
} catch (URISyntaxException ex) {
url="QuestionList.xml";
}
System.out.println(url);
return url;
}
public void classifyQuestionnaire(String path)
throws FileNotFoundException, XMLStreamException, JAXBException {
// Parse the data, filtering out the start elements
XMLInputFactory xmlif = XMLInputFactory.newInstance();
FileReader fr = null;
if (path == null) {
fr = new FileReader(getXmlPath());
} else {
fr = new FileReader(path);
}
XMLEventReader xmler = xmlif.createXMLEventReader(fr);
EventFilter filter = new EventFilter() {
#Override
public boolean accept(XMLEvent event) {
return event.isStartElement();
}
};
You can include xml file into the jar. These non-class files are usually called "resource". It depends on how you're creating the jar, but it's usually straight forward. See Java: Load a resource contained in a jar for reading the resource.

Categories

Resources