My problem is very simple and yet I can't figure out how to solve it.
I have text files in a folder:
"C:/aaa/bbb/ccc/ddd/test.txt"
And excel files in a folder within the text files folder:
"C:/aaa/bbb/ccc/ddd/excelFiles/test.xls"
Both text and excel files have the same name.
I would like to be able to access the path of those excel files.
What I did is:
this.file.getParent()+"\\"+"excelFiles"+"\\"+file.getName().substring(0, fileName.indexOf('.'))+".xls"
I get a "String index out of range" error.
Thank you for your help :)
If I understand your question, one option is to use File.getCanonicalPath() like,
try {
File f = new File("C:/aaa/bbb/ccc/ddd/excelFiles/test.xls");
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
You might want to try this ->
String dynamicExcelFileName = file.getName().substring(0, fileName.indexOf('.'))
into a variable and use it in the path for accessing the excel file.
this way you get to be extra sure to check if the path is properly captured in variable or not and thus less chances of getting index out of range error.
plus the code is more readable
Looking at your snippet, I can see that you're accessing the file's name in two different ways:
file.getName().substring(...)
and
fileName.indexOf(...).
Are you sure that fileName is not empty when you try to determine the index of the dot?
this.file.getParent()+"\"+"excelFiles"+"\"+file.getName().substring(0, this.file.getName().indexOf('.'))+".xls"
This could be achieved quite easily, even without using existing libraries like FileUtils.
These three method can create the corresponding Excel File object for your text object
private File getExcelFile(final File txtFile) throws IOException {
final String path = txtFile.getCanonicalPath();
final String directory = path.substring(0, path.lastIndexOf(System.getProperty("file.separator")));
return new File(getExcelSubdirectory(directory), getExcelFilename(txtFile.getName()));
}
private File getExcelSubdirectory(final String parent) {
return new File(parent, "excelFiles");
}
private static String getExcelFilename(final String filename) {
return filename.substring(0, filename.lastIndexOf('.')) + ".xls";
}
If you use them like this:
File txt = new File("C:/aaa/bbb/ccc/ddd/test.txt");
System.out.println(txt.getCanonicalPath());
File excel = getExcelFile(txt);
System.out.println(excel.getCanonicalPath());
.. it will print:
C:\aaa\bbb\ccc\ddd\test.txt
C:\aaa\bbb\ccc\ddd\excelFiles\test.xls
Related
I have this piece of code in my project:
String readFile() {
String pathname = saveDirectory + fileName + ".txt";
String content = "";
File f = new File(pathname);
if (f.exists() && !f.isDirectory()) {
try {
content = new String(Files.readAllBytes(Paths.get(pathname)));
}
catch (IOException e) { }
}
return content;
}
There are no errors, the aplication runs just right, but the content variable never has any text in it and I'm sure that the txt file has text in it!
I've already tried different ways to read the text file (with BufferedReader, Scanner, FileInputStream and FileReader) but none of them worked.
Ps. I'm almost sure that the problem isn't in the pathname variable since I've tried to open the file via code (with Runtime) and it opened the right file normally.
Ok, I tried adding the e.printStackTrace(); but there is still no errors, and it's not missing a / between the directory and the fileName, i've already added in the \\ in the directory variable.
Could you be forgetting the / between the directory and the file name? Print the content of pathname and see.
Or better: debug your code and see what happens.
It looks like you're opening the file once (File f = new File(pathname);), then trying to read it without using the file object you created. You're probably getting an IOException because Files.readAllBytes(Paths.get(pathname)) can't open the file while f has it open.
I am trying to create a new file using java nio, and I'm running into a createFile error. Error looks like this:
createFile error: java.nio.file.NoSuchFileException: /Users/jchang/result_apache_log_parser_2015/06/09_10:53:49
code segment looks like this:
String filename = "/Users/jchang/result_apache_log_parser_" + filename_date;
Path file = Paths.get(filename);
try {
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
System.err.format("createFile error: %s%n", x);
}
Anyone have any idea how to fix this? Thanks for your help!
I would say that Turing85 was correct. Your filename_date variable has slashes in it. So /Users/jchang/result_apache_log_parser_2015 has to exist as a directory. That is the cause of the NoSuchFileException, missing directory.
Your code has at least two problems. First: you have path delimiters in your filename (/). Second: at least under Windows, your solution has illegal characters within the filname (:).
To get rid of the first problem, you can go down two routes: a) create all the folders you need or b) change the delimiters to something different. I will explain both.
To create all folders to a path, you can simply call
Files.createDirectories(path.getParent());
where path is a file (important!). By calling getParent() on file, we get the folder, in which path resides. Files.createDirectories(...) takes care of the rest.
b) Change the delimiters: Nothing easier than this:
String filename = "/Users/jchang/result_apache_log_parser_"
+ filename_date.replace("/", "_")
.replace(":", "_");
This should yield something like /User/jchang/result_apache_parser_2015_06_09_10_53_29
With b) we have taken care of the second problem as well.
Now lets set it all together and apply some minor tricks of nio:
String filename = "/Users/jchang/result_apache_log_parser_"
+ filename_date.replace('/', '_')
.replace(':', '_');
Path file = Paths.get(filename);
try {
// Create sub-directories, if needed.
Files.createDirectories(file.getParent());
// Create the file content.
byte[] fileContent = ...;
// We do not need to create the file manually, let NIO handle it.
Files.write(file
, fileContent
// Request permission to write the file
, StandardOpenOption.WRITE
// If the file exists, append new content
, StandardOpenOption.APPEND
// If the file does not exist, create it
, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
For more information about nio click here.
As many said, you need to create intermediate directories, like ../06/..
So use this, before creating the file to create dirs which don't exist,
Files.createDirectories(mPath.getParent());
So your code should be:
Path file = Paths.get(filename);
try {
Files.createDirectories(file.getParent());
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
System.err.format("createFile error: %s%n", x);
}
trying to rename internal file within a zip file without having to extract and then re-zip programatically.
example. test.zip contains test.txt, i want to change it so that test.zip will contain newtest.txt(test.txt renamed to newtest.txt, contents remain the same)
came across this link that works but unfortunately it expects test.txt to exist on the system. In the example the srcfile should exist on the server.
Blockquote Rename file in zip with zip4j
Then icame across zipnote on Linux that does the trick but unfortunately the version i have doesnt work for files >4GB.
Any suggestions on how to accomplish this? prefereably in java.
This should be possible using Java 7 Zip FileSystem provider, something like:
// syntax defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/directoryPath/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) {
Path sourceURI = zipfs.getPath("/pathToDirectoryInsideZip/file.txt");
Path destinationURI = zipfs.getPath("/pathToDirectoryInsideZip/renamed.txt");
Files.move(sourceURI, destinationURI);
}
Using zip4j, I am modifying and re-writing the file headers inside of the central directory section to avoid rewriting the entire zip file:
ArrayList<FileHeader> FHs = (ArrayList<FileHeader>) zipFile.getFileHeaders();
FHs.get(0).setFileName("namename.mp4");
FHs.get(0).setFileNameLength("namename.mp4".getBytes("UTF-8").length);
zipFile.updateHeaders ();
//where updateHeaders is :
public void updateHeaders() throws ZipException, IOException {
checkZipModel();
if (this.zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (Zip4jUtil.checkFileExists(file)) {
if (zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
}
long offset = zipModel.getEndCentralDirRecord().getOffsetOfStartOfCentralDir();
HeaderWriter headerWriter = new HeaderWriter();
SplitOutputStream splitOutputStream = new SplitOutputStream(new File(zipModel.getZipFile()), -1);
splitOutputStream.seek(offset);
headerWriter.finalizeZipFile(zipModel, splitOutputStream);
splitOutputStream.close();
}
The name field in the local file header section remains unchanged, so there will be a mismatch exception in this library.
It's tricky but maybe problematic, I don't know..
In Eclipse, when I right click on the file I want to input from in my project, it shows two things:
path: /SWT/src/data.txt
location: C:\Users\Yoshikawa\workspace\SWT\src\data.txt
Is there any way I can get the location (C:\Users\Yoshikawa\workspace\SWT\src\data.txt) is I know just the path (/SWT/src/data.txt) ?
Ex.
public String ReadFile(String file_path) {
//Search current project directory
return file_location
}
public String readFile(String file_path){
File f = new File(file_path);
return f.getAbsolutePath();
}
You attempt to create a File object based on the file_path and then run the method getAbsolutePath() method of the File class.
h
You can read up more on this here: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Hopefully this works.
Take a look at the Java Path Class.
You can use File.getAbsolutePath or File.getCanonicalPath. They are not the same, see the difference
String relativePath = "../1.txt";
System.out.println(new File(relativePath).getCanonicalPath());
System.out.println(new File(relativePath).getAbsolutePath());
output
D:\workspace1\1.txt
D:\workspace1\x\..\1.txt
see java.io.File API for details
I have File object in Java which is a directory path:
C:\foo\foo\bar
...and I would like to change this to:
C:\foo\foo\newname
I'm don't mean renaming the actual directory, but, simply modifying the path in the File object. Could someone show me how I can do this? Do I have to use string functions for this or is there some inbuilt Java function that I can use?
Thanks.
You can construct one File from another and get the parent directory of a file, combining these:
File orig = new File("C:\\foo\\foo\\bar");
File other = new File(orig.getParentFile(), "newname");
There is no such method in java that changes path for the File object, however you can get the file path with getPath() or getAbsolutePath(). I think creating a new file at that path would do.
Try following:
import java.io.File;
public class MainClass {
public static void main(String[] a) {
File file = new File("c:\\foo\\foo\\bar");
file.renameTo(new File("c:\\foo\\foo\\newname"));
}
}
Hope this helps.
You can use the string-representation of the File object and search for the last / with indexOf(), then you change the value after it and create a new File object.
I guess you need to something like this.
String sourcePath = "C:\\foo\\foo\\bar";
String newName = "newname";
File source = new File(sourcePath);
File dest = new File(source.getParent() + File.separator + newName);
source.renameTo(dest);
I think you can only create a new File object with the new path:
File f2 = new File("C:\\foo\\foo\\newname")
Does it make any side effect on your code?