i tried the following program
import java.io.*;
class dr
{
public static void main(String args[])
{
try{
File[] roots = File.listRoots();
for (int index = 0; index < roots.length; index++)
{ //Print out each drive/partition
System.out.println(roots[index].toString());
}
}
catch(Exception e)
{
System.out.println("error " +e);
}
}
}
but in my system floppy drive is not connected
and i am getting a message like the following
" The drive is not ready for use;its door may be open,Please check drive A: and make sure that disk is inserted and that the drive door is closed"
then three options are shown cancel,try again,continue
when i try continue,it works
but how i could avoid that msg
What are you trying to do?
My recommendation would be to use FileSystemView.
It's used something like this:
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (File f: roots) {
System.out.println(fsv.getSystemDisplayName(f);
}
package com.littletutorials.fs;
import java.io.*;
import javax.swing.filechooser.*;
public class DriveTypeInfo
{
public static void main(String[] args)
{
System.out.println("File system roots returned byFileSystemView.getFileSystemView():");
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++)
{
System.out.println("Root: " + roots[i]);
}
System.out.println("Home directory: " + fsv.getHomeDirectory());
System.out.println("File system roots returned by File.listRoots():");
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++)
{
System.out.println("Drive: " + f[i]);
System.out.println("Display name: " + fsv.getSystemDisplayName(f[i]));
System.out.println("Is drive: " + fsv.isDrive(f[i]));
System.out.println("Is floppy: " + fsv.isFloppyDrive(f[i]));
System.out.println("Readable: " + f[i].canRead());
System.out.println("Writable: " + f[i].canWrite());
System.out.println("Total space: " + f[i].getTotalSpace());
System.out.println("Usable space: " + f[i].getUsableSpace());
}
}
}
reference : http://littletutorials.com/2008/03/10/getting-file-system-details-in-java/
When it comes to Windows, this class WindowsAltFileSystemView proposes an alternative based on FileSystemView
This class is necessary due to an annoying bug on Windows NT where instantiating a JFileChooser with the default FileSystemView will cause a "drive A: not ready" error every time.
I grabbed the Windows FileSystemView impl from the 1.3 SDK and modified it so * as to not use java.io.File.listRoots() to get fileSystem roots.
java.io.File.listRoots() does a SecurityManager.checkRead() which causes the OS to try to access drive A: even when there is no disk, causing an annoying "abort, retry, ignore" popup message every time we instantiate a JFileChooser!
So here, the idea is to extends FileSystemView, replacing the getRoots() method with:
/**
* Returns all root partitians on this system. On Windows, this
* will be the A: through Z: drives.
*/
public File[] getRoots() {
Vector rootsVector = new Vector();
// Create the A: drive whether it is mounted or not
FileSystemRoot floppy = new FileSystemRoot("A" + ":" + "\\");
rootsVector.addElement(floppy);
// Run through all possible mount points and check
// for their existance.
for (char c = 'C'; c <= 'Z'; c++) {
char device[] = {c, ':', '\\'};
String deviceName = new String(device);
File deviceFile = new FileSystemRoot(deviceName);
if (deviceFile != null && deviceFile.exists()) {
rootsVector.addElement(deviceFile);
}
}
File[] roots = new File[rootsVector.size()];
rootsVector.copyInto(roots);
return roots;
}
you can use this;
import java.io.File;
class dr
{
public static void main(String args[])
{
File[] roots=File.listRoots();
for(File root:roots)
{
System.out.println(root.getName());
}
}
}
Related
I'm trying to write a program to quickly rename some files in a folder.
The files are named like this:
C:\Users\user\Documents\Reports\Report FirstName LastName.FileNameExtension
I'd like to rename them like this:
C:\Users\user\Documents\Reports\Report LastName FirstName.FileNameExtension
This is my code so far:
public class FileRenamer {
public static void main(String[] args) {
List<String> filePaths = new ArrayList<String>();
try(Stream<Path> paths = Files.walk(Paths.get(args[0]))) {
paths.forEach(filePath -> {
filePaths.add(filePath.toString());
});
} catch (IOException e) {
e.printStackTrace();
}
filePaths.forEach(filePath -> {
String[] splitPath = filePath.split(" ");
String fileNameExtension = splitPath[2].split(".")[1];
splitPath[2] = splitPath[2].split(".")[0];
String newFilePath = splitPath[0] + " " + splitPath[2] + " " +
splitPath[1] + "." + fileNameExtension;
new File(filePath).renameTo(new File(newFilePath));
});
}
}
My problem is that it keeps throwing an ArrayIndexOutOfBoundsException for the splitPath array. But it doesn't throw an exception when I'm running a for-loop to output the indexes from 0 to 2. What am I doing wrong?
EDIT: This is the working for-loop
for(int i = 0; i < splitPath.length; i++) {
System.out.println(i + ": " + splitPath[i]);
}
It outputs this to the console:
0: C:\Users\user\Documents\Reports\Report
1: FirstName
2: LastName.FileNameExtension
Files.walk() not only prints the regular files in the directory, but also the directory itself and any hidden files. Those will likely not fit your pattern.
Files.walk(Paths.get("/home/joost"), 1).forEach(p -> System.out.println(p.toString()));
/home/joost
/home/joost/someRegularFile.jpg
/home/joost/.profile
...
Also, Path::toString() gives to the full path, not just the filename. So if any of the directories in your path has a space in it, you will get unexpected results.
I am creating a JAVA program to copy certain folders to a new location automatically, to do this I created a function with a loop to use the same function for each given folder source and destination. The problem is that the function will just copy the first folder to the new location multiple times instead of copying it once then copying the next folder. The folder locations are held in a string array and a specific one is selected by changing value [i]. Each time the function loops [i] increases but the loop does not select the [i] value as well as the next folder to copy.
Is anyone able to help me with this, the code i am working with is below, Thanks.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Application {
static String[] saves = {
"C:\\Users\\Lucas\\Documents\\My Games\\Halo",
"C:\\Users\\Lucas\\Documents\\My Games\\Terraria",
"C:\\Users\\Lucas\\Documents\\My Games\\Borderlands 2",
"C:\\Users\\Lucas\\Documents\\My Games\\Rocket League"
};
private static int i = 1;
File source = new File(saves[i]);
static File folder = new File("Saves\\");
File dest = new File(String.valueOf(folder) + "\\" + source.getName());
private void Start() throws IOException {
MakeDirectory(folder);
Copy();
}
private void Copy() throws IOException {
copyFileUsingJava7Files(source, dest);
Add();
}
private void Add() throws IOException {
i++;
System.out.println("Value of i = " + i);
System.out.println("");
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
if (!dest.exists()) {
System.out.println("Copying files from: " + "'" + source + "'");
System.out.println("");
copyFolder(source, dest);
System.out.println("File copied");
} else {
copyFolder(source, dest);
}
}
private static void copyFolder(File source, File dest) throws IOException {
if (source.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory created :: " + dest);
}
String files[] = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
if (source.lastModified() > dest.lastModified()) {
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + dest);
} else {
System.out.println("A newer version exists of: " + "'" + dest + "'");
}
}
}
private static void MakeDirectory(File folder) {
if (!folder.exists()) {
System.out.println("Creating directory: " + "'" + folder + "'");
folder.mkdir();
System.out.println("Directory created");
} else {
System.out.println("Directory already exists: " + "'" + folder + "'");
}
}
public static void main(String[] args) throws IOException {
Application app = new Application();
int l;
for (l = 0; l < 3; l++) {
app.Start();
}
}
}
It doesn't look like you're ever changing the source field after setting it initially. You're setting it to the second file, but then not changing it later. Incrementing i won't automatically update source because source is just a File.
Also, you're starting with i = 1. In Java, arrays are zero-indexed, which means that the first item in the array is actually item 0, so you should be starting with i = 0 instead.
You have to reinitialize File source each time, you increase i. Otherwise, the source won't be changed.
Since i is a static variable, all objects share the same variable. Since you are incrementing the i during each app.Start() method, at the end of calling 5 times, its value is 5. Consequently you get the output as 5 in all your sys outs. Thats the point of static.
I want to write a program in java to search a string in entire workspace using eclipse search plugin in my code.
I have searched for this problem but couldnt find the result.
Kindly help.
Every suggestion is appreciated.
Thanks in advance.
You do realize that there already is such a functionality in Eclipse, do you? In Eclipse Search -> File... enter your text, select *.* as the File name patterns, and workspace as Scope.
Or do you maybe want to write a plugin that uses this search internally?
From your comments I get the picture that you are looking for code to loop through directories/files and search through them. Maybe this question can help you there.
Use something like the following to recurse through all the projects and folders for file:
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
// Get all the projects in the workspace
IProject [] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
// Search each project
for (IProject project : projects)
{
searchContainer(project);
}
/*
* Search a project or folder.
*/
private void searchContainer(IContainer container)
{
// Get all the resources in the container
IResource [] members = container.members();
// Look at each resource
for (IResource member : members)
{
if (member instanceof IContainer)
{
// Resource is a folder, search that
searchContainer((IContainer)member);
}
else if (member instanceof IFile)
{
// Resource is a file, search that
searchFile((IFile)member);
}
}
}
/*
* Search a file.
*/
private void searchFile(IFile file)
{
// TODO search the file
}
You should run this in a Job or other background task as it may take some time to run.
package search_workspace09;
import java.io.*;
import java.util.regex.*;
public class workspace_search09
{
public static void main(String args[])
{
try
{
String dirName="D:/test_folder";
String stringsearch="world";
//String fileName = "test.txt";
File dir = new File(dirName);
// Open the file c:\test.txt as a buffered reader
File[] dirs=dir.listFiles();
if(dirs!=null)
{
for (int i=0;i<dirs.length;i++)
{
if(dirs[i].isFile())
{
File filename=dirs[i];
System.out.println("Files to search in " +filename);
BufferedReader bf=new BufferedReader(new FileReader(filename));
//System.out.println(filename);
// Start a line count and declare a string to hold our current line.
int countline=0;
String line;
//pattern search
Pattern p = Pattern.compile("\\b"+stringsearch+"\\b", Pattern.CASE_INSENSITIVE);
System.out.println("Search Criteria " +" Filename\t\t\t"+ " Line no. " + " Position\t" + " Line Text ");
while ( (line = bf.readLine()) != null)
{
// Increment the count and find the index of the word
countline++;
Matcher m = p.matcher(line);
// indicate all matches on the line
while(m.find())
{
System.out.println(stringsearch +"\t\t"+ filename+"\t\t" + countline + "\t " + m.start() + "\t"+line);
}
}
//continue;
}
}}}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}}}
public class workspace_search14
{
public static void main(String[] args)throws IOException
{
String dir="D:/test_folder";
File root=new File(dir);
findFiles(root,0);
}
public static void findFiles(File root,int depth) throws IOException
{
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile())
{
if (iName.endsWith(".txt") || iName.endsWith(".TXT")||iName.endsWith(".java"))
{
for (int j = 0; j < depth; j++)
System.out.print("\t");
System.out.println("\nFile_Name: "+iName);
searchFiles(listOfFiles[i]);
}
}
else if (listOfFiles[i].isDirectory())
{
for (int j = 0; j < depth; j++)
System.out.print("\t");
System.out.println("\nDirectory_Name: "+iName);
findFiles(listOfFiles[i], depth+1);
}
}
}
public static void searchFiles(File FileName)throws IOException
{
int countline=0;
String line;
String stringsearch="world";
BufferedReader bf=new BufferedReader(new FileReader(FileName));
Pattern p = Pattern.compile("\\b"+stringsearch+"\\b", Pattern.CASE_INSENSITIVE);
System.out.println("Search Criteria " +" Filename\t\t\t"+ " Line no. " + " Position\t" + " Line Text ");
while ( (line = bf.readLine()) != null)
{
countline++;
Matcher m = p.matcher(line);
while(m.find())
{
System.out.println(stringsearch +"\t\t"+ FileName+"\t\t" + countline + "\t " + m.start() + "\t"+line);
}}}}
I always get a false return from isDirectory() method when the folder name contains specials chars like ó or ñ.
The Java code works fine in DOS, I have the problem executing jar in my NAS (Linux).
public static void listarDirectorio(File f, String separador)
throws Exception {
File[] ficheros = f.listFiles();
File ficheroTratado = null;
for (int x = 0; x < ficheros.length; x++) {
ficheroTratado = null;
ficheroTratado = ficheros[x].getCanonicalFile();
if (!ficheroTratado.isDirectory()) {
System.out.println(
"Checking file: " + ficheroTratado.getName());
if (esBorrable(ficheroTratado.getName())) {
System.out.println(
"File can be erased: " + ficheroTratado.getName());
}
}else if (!ficheros[x].getName().startsWith("#")) {
String nuevo_separador;
nuevo_separador = separador + " # ";
listarDirectorio(ficheros[x], nuevo_separador);
}
}
}
I am working on a code to rename number of files in java. I have a list of the files in a .txt. File in which my program retreives the name of the document and its new name. It currently does not work.. It compiles and run but it wont rename my files.
Here's my code:
public static void rename(String ol, String ne){
File oldfile =new File(ol);
File newfile =new File(ne);
int t=0;
if( oldfile.isFile() && oldfile.canRead()){
if (newfile.exists()){
t++;
ne = ne.substring(0,ne.lastIndexOf('.')) + " (" + t + ")" +
ne.substring(ne.lastIndexOf('.')) ;
rename(ol,ne);
}
if(oldfile.renameTo(newfile))
System.out.println("Rename succesful");
else
System.out.println("Rename failed" + " - " + ol + " " + ne);
}else
System.out.println("CANNOT Rename " + oldfile + " because read/write issues. Check
if File exists" );
}
public static void main(String[] args) throws IOException
{
ReadFile ren = new ReadFile("List of Founds.txt");
String r[] = ren.OpenFile();
for(int j=0; j<ReadFile.numberOfLines; j++){
String pdfOldName = r[j].substring(0,r[j].lastIndexOf('.'));
String pdfNewName = r[j].substring((r[j].lastIndexOf('.') + 4));
rename(pdfOldName, pdfNewName);
}
}
This is the 'List of founds' .txt file, the old name is on the left and the new name is on the right.
test.pdf.txt ayo1
test2.pdf.txt ayo2
test3.pdf.txt ayo3
You can use the File.html#renameTo(java.io.File) to accomplish this.
Heres a quick sample program i wrote.
hope this puts you in right direction
public class FileMain {
static int i = 1;
public static void main(String[] args) throws Exception {
File file1 = new File("D:/workspace/dir");
renamefiles(file1);
}
private static void renamefiles(File file){
File files[] = file.listFiles();
for(File tempFile :files){
if(tempFile.isDirectory()){
renamefiles(tempFile);
}else{
System.out.println(tempFile.getName());
File renameFile = new File("sample-"+(++i)+".bck");
tempFile.renameTo(renameFile);
}
}
}
}
You need a !
if (newfile.exists())
to
if (!newfile.exists())
You also need to follow conventions. And Unit Test.