Failed to move file to another directory using renameTo - java

import java.io.File;
import org.apache.commons.io.FilenameUtils;
public class Tester {
public static void main(String[] args) {
String rootPath = "F:\\Java\\Java_Project";
File fRoot = new File(rootPath);
File[] fsSub = fRoot.listFiles();
for (File file : fsSub) {
if(file.isDirectory()) continue;
String fileNewPath = FilenameUtils.removeExtension(file.getPath()) + "\\" + file.getName();
File fNew = new File(fileNewPath);
try {
file.renameTo(fNew);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to move the file to another directory,for instance,if the File path is
"C:\out.txt"
than I want to move to
"C:\out\out.txt"
If i try to print the original File and the new original information, the work well,But they just can not move successful.

I suggest to try Java 7 NIO2
Files.move(Path source, Path target, CopyOption... options)

Related

Printing contents of an imported class to console in java

I'm programming in an online IDE (it is studio.code.org) (For a programming course). I would like to switch to a local IDE, but the online IDE uses some imports that are unavailable to download, but can be used in the code that has been written in the online IDE. This is in java. To make this a more general form of question that applies to (and will help) most people:
This is in java. I'm trying to print the contents of a file out in the console whose path is unknown, but is used as an import. Is it possible? If so, what code do I need to run to print the file out in console (from where I can copy paste it and use it elsewhere).
Here's the source code for something I tried to make this happen (but it didn't work, I'll show what output I got from the console below the code):
import java.io.*;
import org.code.neighborhood.Painter;
public class MyNeighborhood {
public static void main(String[] args) {
try {
Class<?> cls = Class.forName("org.code.neighborhood.Painter");
String fileName = cls.getName().replace('.', File.separatorChar) + ".class";
File file = new File(fileName);
System.out.println("File path: " + file.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
fis.close();
System.out.println(new String(buffer));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output from console:
[JAVALAB] Connecting...
[JAVALAB] Compiling...
[JAVALAB] Compilation successful.
[JAVALAB] Running...
File path: /tmp/org/code/neighborhood/Painter.class
As you may have noticed I have found a file, but it is empty, although I know that the real file that is being imported is certainly not empty.
I do have read access to the system as well since I am able to navigate the root folder by using the code below:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
boolean readContent = false; // change this to true to read file content, false to read file names
File directory = new File("/");
if (readContent) {
String fileName = "";
readFileContent(directory, fileName);
} else {
String[] fileNames = readFileNames(directory);
if (fileNames == null) {
System.out.println("Directory not found.");
} else {
System.out.println("Files in the directory:");
for (String fileName : fileNames) {
File file = new File(directory, fileName);
if (file.isDirectory()) {
System.out.println("Directory: " + fileName);
} else if (file.isFile()) {
System.out.println("File: " + fileName);
}
}
}
}
}
private static void readFileContent(File directory, String fileName) {
File file = new File(directory, fileName);
if (file.isFile()) {
try (FileReader reader = new FileReader(file)) {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File not found.");
}
}
private static String[] readFileNames(File directory) {
if (directory.isDirectory()) {
return directory.list();
}
return null;
}
}

How to print to csv file?

I wrote a script to print the names of all files and folders, recursively, to console. I want to edit this to print it in an excel spreadsheet/csv like so :
Folder
FullPath/Folder/File.extension, Folder, Extension
...
...
Recursively do this for all documents in the folder.
Here is my script to do it in Console :
package test;
import java.io.File;
import java.io.IOException;
public class RecursiveFileDisplay {
public static void main(String[] args) {
File currentDir = new File("."); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
How can I adapt this to print to an Excel spreadsheet or CSV?
Thanks.

Java - Can't find and load a CSV file

For some reason, although I have already downloaded the CSV files, my program is unable to read them. My code is below, and it checks if the CSV file exists. If it does not, it goes to the URL and downloads and reads the code. However, it always re-downloads the code although it is in the path folder.
private void loadData(String path, String url) throws IOException{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
This code outputs
looking for path C:\Users\n_000\workspace\Program\GOOG.csv
Need to download from internet.
looking for path C:\Users\n_000\workspace\Program\CHK.csv
Need to download from internet.
The code that I'm using to create the path is this:
String save = "filename"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
path = savedFolder+save+".csv";
Its working fine,i didn't see any issues,i am posting my tested code,hope it may be useful.
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String ar[])
{
Test test=new Test();
}
public Test()
{
String save = "GOOG"; //in program use this is the name of the stock eg GOOG or CHK
Path currentRelativePath = Paths.get("");
String savedFolder = currentRelativePath.toAbsolutePath().toString() + "\\";
String path = savedFolder+save+".csv";
String url=null;
try
{
loadData(path,url);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void loadData(String path, String url) throws IOException
{
File f = new File(path);
System.out.println("looking for path " + path);
if(f.exists()) {
readSavedFile(path); //method to load data
}
else{
System.out.println("Need to download from internet");
downloadAndRead(url, path);
}
}
public void readSavedFile(String path)
{
System.out.println("Reading file");
}
public void downloadAndRead(String url,String path)
{
System.out.println("Downloding file");
}
}

Java Crop all Images in Folder

Working on Java code to crop all images in folder using java code, processbuilder, This code is working but, its only doing for first file, other files not doing..Please help me!! Thanks!!
Here is my code:
import java.io.File;
import java.io.IOException;
public class test1 {
/**
* #param args
*/
public static void main(String argv[]) throws IOException, InterruptedException {
// TODO Auto-generated method stub
try {
File folder = new File("Map_Image");
File[] BFFile = folder.listFiles();
String full_path = null;
String new_path = null;
for (File file : BFFile) {
String str = file.getName();
System.out.println("Image File:- " + str);
full_path = file.getAbsolutePath();
new_path = folder + "\\" + "new_" + str;
System.out.println("New Image Files:- " + new_path);
try {
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "C:\\Program Files\\ImageMagick-6.8.8-Q16\\convert.exe", "-crop", "512x512+0-20", full_path, new_path);
Process p = pb.start();
p.waitFor();
} catch(Exception error1) {
error1.printStackTrace();
}
}
} catch(Exception error) {
error.printStackTrace();
}
}
}
Code it working but, it's only doing for first files its not doing for other files..
Output:
Image File:- address_map.jpg
New Image Files:- Map_Image\new_address_map.jpg
Image File:- Michael Couse_200857860.jpg
New Image Files:- Map_Image\new_Michael Couse_200857860.jpg
ProcessBuilder only running one time, its not running for others files..
Please help me!!
Thanks in Advanced!!
Unfortunately, listFiles is quite buggy (especially with unicode names). What you can use is:
try (DirectoryStream ds = Files.newDirectoryStream(folder))
{
for (Path file : ds) {
// Your code goes here
}
}
catch (IOException e) {
e.printStackTrace();
}
That is not to say it will certainly fix your issue, but it's worth a try.

How to get absolute paths of files in a directory?

I have a directory with files, directories, subdirectories, etc. How I can get the list of absolute paths to all files and directories using the Apache Hadoop API?
Using HDFS API :
package org.myorg.hdfsdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class HdfsDemo {
public static void main(String[] args) throws IOException {
Configuration conf = new Configuration();
conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/core-site.xml"));
conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/hdfs-site.xml"));
FileSystem fs = FileSystem.get(conf);
System.out.println("Enter the directory name :");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Path path = new Path(br.readLine());
displayDirectoryContents(fs, path);
}
private static void displayDirectoryContents(FileSystem fs, Path rootDir) {
// TODO Auto-generated method stub
try {
FileStatus[] status = fs.listStatus(rootDir);
for (FileStatus file : status) {
if (file.isDir()) {
System.out.println("This is a directory:" + file.getPath());
displayDirectoryContents(fs, file.getPath());
} else {
System.out.println("This is a file:" + file.getPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writer a recursive function which takes a file and check if its a directory or not, if directory list out all files in it and in a for loop check if the file is a directory then recursively call or just return the list of files.
Something like this below but not exactly same (here I am returning only .java files)
private static List<File> recursiveDir(File file) {
if (!file.isDirectory()) {
// System.out.println("[" + file.getName() + "] is not a valid directory");
return null;
}
List<File> returnList = new ArrayList<File>();
File[] files = file.listFiles();
for (File f : files) {
if (!f.isDirectory()) {
if (f.getName().endsWith("java")) {
returnList.add(f);
}
} else {
returnList.addAll(recursiveDir(f));
}
}
return returnList;
}
with hdfs you can use hadoop fs -lsr .

Categories

Resources