How to assign ArrayList of String to File[] in java. I have tried as shown below
ArrayList<String> fileList;
File[] file;
for (int i = 0; i < fileList.size(); i++) {
file = new File (fileList.get(i));
}
But I am getting file cannot be converted to File[]. Please correct me.
First, you need to initialize the array like
File[] file = new File[list.size()];
Now, you need to access the indexes of the array, like
for(int i = 0;i<fileList.size();i++) {
file[i] = new File(list.get(i));
}
Related
I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.
I'm making a program where I store a songs' title, artist, and genre into into a data file. Like this:
public void writeSong(Song t) throws IOException {
File myFile = new File(Song.getFileInput());
RandomAccessFile write = new RandomAccessFile(myFile,"rw");
write.writeChars(title);
write.writeChars(artist);
write.writeChars(genre);
write.close();
}
After I do that, I'm supposed to read the data file and display the contents of it like this:
public Song readSong() throws FileNotFoundException, IOException {
File myFile = new File(Song.getFileInput());
RandomAccessFile read = new RandomAccessFile(myFile, "rw");
String readTitle = null, readArtist = null, readGenre = null;
Song so = null;
read.seek(0);
for(int i = 0; i < title.length(); i++){
readTitle += read.readChar();
}
read.seek(50);
for(int i = 0; i < artist.length(); i++){
readArtist += read.readChar();
}
read.seek(100);
for(int i = 0; i < genre.length(); i++){
readGenre += read.readChar();
}
so = new Song(readTitle, readArtist, readGenre);
read.close();
return so;
}
If I assign it to a file called "songs.dat", it's supposed to write and read the songs off that file. After I exit the program and run it again, I make the file called "songs.dat" again. But when I want to read and display the songs, nothing happens. Does anyone how to resolve this problem?
RandomAccessFile.seek(long position) set the file position where you want to read or write.
When you begin to read your file you set the position to 0 with read.seek(0). But from there you dont need to reset it :
public Song readSong() throws FileNotFoundException, IOException {
File myFile = new File(Song.getFileInput());
RandomAccessFile read = new RandomAccessFile(myFile, "rw");
String readTitle = "", readArtist = "", readGenre = "";
Song so = null;
read.seek(0);
for(int i = 0; i < title.length(); i++){
readTitle += read.readChar();
}
for(int i = 0; i < artist.length(); i++){
readArtist += read.readChar();
}
for(int i = 0; i < genre.length(); i++){
readGenre += read.readChar();
}
so = new Song(readTitle, readArtist, readGenre);
read.close();
return so;
}
I also initialize your String to empty String so you dont have "null" string in the first place as a result
How to search a particular folder for a file name, that is input by the user. In my program the file is an excel spreadsheet. So if i basically use:
Scanner kbReader = new Scanner(System.in);
String fileName = kbReader.nextLine();
How would i search and open the corresponding file with the name fileName.
You need to use regular expression to match your file name like filename.matches("*"+expectedfilename+"*.xls")) on List of file names taken from directory.
String fileName = null;
File folder = new File("your/directory/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
fileName = listOfFiles[i].getName();
if(fileName.matches("*"+expectedfilename+"*.xls"))){ // put regex here
// do your code here and
// if you want to open do operation on file then file object
File file = listOfFiles[i];
}
}
}
Try this
File dir = new File("F:/");
File[] allFileName = dir.listFiles();
for (int i = 0; i < allFileName.length; i++) {
String filename = allFileName[i].getName()
if (allFileName[i].isFile()) {
if (filename.endsWith(".xls"))
System.out.println("This is a excel file with name " + filename);
}
}
I am trying to delete all the files inside a directory then the directory afterwards using the below code but it doesn't seem to work. (Files are not deleted after the method ran).
public void DeleteDirectory() {
ArrayList<File> Directories = new ArrayList<File>();
Directories.add(new File(Environment.getExternalStorageDirectory().toString().concat("/AssetControl/Images")));
Directories.add(new File(Environment.getExternalStorageDirectory().toString().concat("/AssetControl/Thumbnails")));
ListIterator<File> itr = Directories.listIterator();
while (itr.hasNext()) {
File dir = itr.next();
if (dir.isDirectory()) {
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
(new File(files[i])).delete();
// This is also not working:
// File current = new File(files[i]);
// current.delete();
}
dir.delete();
}
}
}
This worked for me:
replaced String[] files with File[] files.
while (itr.hasNext()) {
File dir = itr.next();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
DeleteFile(files[i]);
}
dir.delete();
}
}
I know there's a way to select a random file from a directory, but I don't know how it's coded in Java. I have pseudocode though. What I'm asking is if I could get a nudge in the right direction. My pseudocode is as follows:
dir = "directory";
String[] files = dir.listfiles();
String next = rand.nextInt(files.length);
Image img = next;
The reason I want to do it like this is because I have a long list of images that I would like to shuffle through.
Your pseudo code looks fine, you can get all the names recursively, store the names in an ArrayList, and randomly retrieve the names from the ArrayList as shown below:
static ArrayList<String> files = new ArrayList<String>();
public static void main(String[] args) {
File dir = new File(".");
getFileNames(dir);
Random rand = new Random();
String next = files.get(rand.nextInt(files.size()));
}
private static void getFileNames(File curDir) {
File[] filesList = curDir.listFiles();
for (File f : filesList) {
if (f.isDirectory())
getFileNames(f);
if (f.isFile()) {
files.add(f.getName());
}
}
}
You seem to be on the right track. Only thing is listFiles() returns a File[] not a String[]
Maybe try something like this
File file = new File(filename);
File[] files = new File[0]; // initialize
if (file.isDirectory()){
files = file.listFiles(); // populate
}
int fileIndex = new Random().nextInt(files.length); // get random index
Image img = new ImageIcon(files[fileIndex]).getImage(); // create image
Though the above may work, It's recommended using URL for embedded resources and not Files. Something like this
String[] filenames = file.list(); // list returns String
int fileIndex = new Random().nextInt(filenames.length);
Image img = null;
java.net.URL url = MyClass.class.getResource(filenames[fileIndex]);
if (url != null){
img = new ImageIcon(url).getImage();
} else {
img = null;
}
When using the class.gerResource(). The file will be searched for in the location of the class files. You can can also change the path a little bit, for example if you want a file structure like this
ProjectRoot
bin
MyClass.class
images
image1.png
image2.png
src
Then you can use this code
java.net.URL url = MyClass.class.getResource("images/" + filenames[fileIndex]);
Here is how I would implement your pseudo-code
private static final Random random = new Random(0x20131224 ^ // A seed value
System.currentTimeMillis()); // and more seed value(s).
public static File getRandomFile(String filePath) {
File f = new File(filePath); // Do we have a directory?
if (f == null || ! f.isDirectory()) {
return f;
}
File[] files = f.listFiles();
List<File> al = new ArrayList<File>();
for (File file : files) {
if (file != null && file.isFile() && file.canRead()) { // Make sure it's a file.
al.add(file);
}
}
return al.get(random.nextInt(al.size())); // Get a random file.
}
File filedir=new File("C:\\Users\\ramaraju\\Desktop\\japan02-12\\");
File[] files=filedir.listFiles();
Random generator = new Random();
int Low = 0;
int High = files.length;
int R = generator.nextInt(High-Low) + Low;
System.out.println(R);
for (int i = 0; i < files.length; i++) {
if(i==R)
{
System.out.println(files[i].getName());
}
}