Java - IOException: The system cannot find path specified - java

import java.io.File;
import java.io.IOException;
public class TestFile {
public static void main(String[] args) {
String separator = File.separator;
String filename = "myFile.txt";
String directory = "mydir1" + separator + "mydir2";
File f = new File(directory,filename);
if (f.exists()) {
System.out.print("filename:" + f.getAbsolutePath());
System.out.println("filesize:" + f.length());
} else {
f.getParentFile().getParentFile().mkdir();
try{
f.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
What I am trying to do is create file "myFile.txt" under the folder "mydir1", but the console says "the system cannot find the path specified", can someone tell me where did I do wrong? Thanks in advance.

It looks like you create only mydir1 but not mydir2.
I can suggest instead of
f.getParentFile().getParentFile().mkdir();
try something like:
f.getParentFile().mkdirs();
File.mkdirs will try to create all required parrent directories.

Related

how to increment number in new file name?

Hi there I am currently writing a method in Java where I am trying to create new files but I need those files not to be of the same name, but rather of incrementing name values, like so:
/Users/Myself/Desktop/myFile0.xml
/Users/Myself/Desktop/myFile1.xml
/Users/Myself/Desktop/myFile2.xml
/Users/Myself/Desktop/myFile3.xml
So I have tried to do the following in my code, but I do not understand why when I call the file within the for each loop ( to create a new one) the number does not increment?
public void pickFolder() throws Exception {
chooserFolder.setDialogTitle("Specify your save location");
chooserFolder.setDialogType(JFileChooser.SAVE_DIALOG);
int numbers = 0;
chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml"));
chooserFolder.setFileFilter(new FileNameExtensionFilter("xml file", "xml"));
int userSelection = chooserFolder.showSaveDialog(null);
if (userSelection == JFileChooser.APPROVE_OPTION) {
for (File file : files) {
chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));
fileToSave = chooserFolder.getSelectedFile();
if (fileToSave.createNewFile()) {
System.out.println("File is created!");
fileToSave = chooserFolder.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null, "File already exists.");
}
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
Any help would be greatly appreciated, Thank you!
What I'm seeing in your code is that you set numbers to ZERO right before incrementing it. try putting int numbers=0 out of your loop if there is any! (you have not written any loop in the code). And of course giving more information would be helpful.
your for-loop has no counter which can be increased, because it is a for-each-loop (if that is the loop you mean). also you call chooserFolder.setSelectedFile(new File("myFile" + numbers++ + ".xml")); only once and there is the only occurrence of numbers++. To given an proper solution you would need to provide all the code. also this line makes no sense at all chooserFolder.setSelectedFile(new File(chooserFolder.getSelectedFile().getAbsolutePath()));. once you give all the code we can provide a solution
Please use the timestamp solution for this problem
String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());
Here have a better example below
package com.seleniummaster.examplefile;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CreateFileWithTimeStamp {
public static void main(String[] args)
{
CreateFileWithTimeStamp("test");
}
//Create a new file
public static void CreateFileWithTimeStamp(String filename) {
//get current project path
String filePath = System.getProperty("user.dir");
//create a new file with Time Stamp
File file = new File(filePath + "\\" + filename+GetCurrentTimeStamp().replace(":","_").replace(".","_")+".txt");
try {
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created; file name is " + file.getName());
} else {
System.out.println("File already exist");
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Get current system time
public static String GetCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");// dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
// Get Current Host Name
public static String GetCurrentTestHostName() throws UnknownHostException {
InetAddress localMachine = InetAddress.getLocalHost();
String hostName = localMachine.getHostName();
return hostName;
}
// Get Current User Name
public static String GetCurrentTestUserName() {
return System.getProperty("user.name");
}
}

Java can't read a text file

I am trying to read a .txt file and search for a word, but the program just closes with Process finished with exit code 0.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class LogParser {
static Scanner file;
static ArrayList text = new ArrayList();
static String path = new String();
static String check = new String();
private static int a = 0;
static Scanner inpunt = new Scanner(System.in);
public static void main (String[] args) {
System.out.println("Input path to file");
path = inpunt.nextLine();
File texts = new File(path);
try {
file = new Scanner(new File(path));
} catch (Exception e) {
System.out.println("Can't open file");
}
try {
while (file.hasNext()) {
text.add(a, file.nextLine());
check = text.get(a).toString();
if (check.contains("cap"))
System.out.println("Allert!!!!!!!!!!!!!!!!!!!!!!!!!!!" + text.get(a));
a = a + 1;
}
} catch (Exception e) {
// System.out.println("Can't open file");
if (file.toString().contains("cap"))
System.out.println("cap" + "Path to file: " + path);
System.out.println(text.size());
}
}
}
The text in the .txt file is:
let's try read this cap
If I try to open an xml file, everything is ok. My problem is only in txt files.
As mentioned in the comments, your path variable isn't set. You're trying to create a new file and passing in a path that hasn't been instantiated.

Trying to copy files in specified path with specified extension and replace them with new extension

I have most of it down but when I try to make the copy, no copy is made.
It finds the files in the specified directory like it is supposed to do and I think the copy function executes but there aren't any more files in the specified directory. Any help is appreciated. I made a printf function that isn't shown here. Thanks!
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import static java.nio.file.StandardCopyOption.*;
public class Stuff {
static String path, oldExtn, newExtn;
static Boolean delOrig = false;
private static void getPathStuff() {
printf("Please enter the desired path\n");
Scanner in = new Scanner(System.in);
path = in.next();
printf("Now enter the file extension to replace\n");
oldExtn = in.next();
printf("Now enter the file extension to replace with\n");
newExtn = in.next();
in.close();
}
public static void main(String[] args) {
getPathStuff();
File folder = new File(path);
printf("folder = %s\n", folder.getPath());
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.getName().endsWith(oldExtn)) {
printf(fileEntry.getName() + "\n");
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
try {
printf("fileEntry = %s\n", fileEntry.toPath().toString());
Files.copy(fileEntry.toPath(), newFile.toPath(),
REPLACE_EXISTING);
} catch (IOException e) {
System.err.printf("Exception");
}
}
}
}
}`
The problem is that the new file is created without a full path (only the file name). So your new file is created - only not where you expect...
You can see that it'll work if you'll replace:
File newFile = new File(FilenameUtils.getBaseName(fileEntry
.getName() + newExtn));
with:
File newFile = new File(fileEntry.getAbsolutePath()
.substring(0,
fileEntry.getAbsolutePath()
.lastIndexOf(".")+1) + newExtn);

Extracting tar.gz using java error

I am trying to extract an archive .tar.gz using java and I am getting Directory error that I do not seem to understand. Please help. I got this sample code from https://forums.oracle.com/forums/thread.jspa?threadID=2065236
package untargz;
import java.io.*;
import com.ice.tar.*;
import javax.activation.*;
import java.util.zip.GZIPInputStream;
/**
*
* #author stanleymungai
*/
public class Untargz {
public static InputStream getInputStream(String tarFileName) throws Exception{
if(tarFileName.substring(tarFileName.lastIndexOf(".") + 1, tarFileName.lastIndexOf(".") + 3).equalsIgnoreCase("gz")){
System.out.println("Creating an GZIPInputStream for the file");
return new GZIPInputStream(new FileInputStream(new File(tarFileName)));
}else{
System.out.println("Creating an InputStream for the file");
return new FileInputStream(new File(tarFileName));
}
}
private static void untar(InputStream in, String untarDir) throws IOException {
System.out.println("Reading TarInputStream... ");
TarInputStream tin = new TarInputStream(in);
TarEntry tarEntry = tin.getNextEntry();
if(new File(untarDir).exists()){
while (tarEntry != null){
File destPath = new File(untarDir + File.separatorChar + tarEntry.getName());
System.out.println("Processing " + destPath.getAbsoluteFile());
if(!tarEntry.isDirectory()){
FileOutputStream fout = new FileOutputStream(destPath);
tin.copyEntryContents(fout);
fout.close();
}else{
destPath.mkdir();
}
tarEntry = tin.getNextEntry();
}
tin.close();
}else{
System.out.println("That destination directory doesn't exist! " + untarDir);
}
}
private void run(){
try {
String strSourceFile = "C:/AskulInstaller/pid.tar.gz";
String strDest = "C:/AskulInstaller/Extracted Files";
InputStream in = getInputStream(strSourceFile);
untar(in, strDest);
}catch(Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
new Untargz().run();
}
}
Once I run this piece of code, this is My Output;
Creating an GZIPInputStream for the file
Reading TarInputStream...
That destination directory doesn't exist! C:/AskulInstaller/Extracted Files
BUILD SUCCESSFUL (total time: 0 seconds)
When I Manually Create the destination Directory C:/AskulInstaller/Extracted Files
I get this Error Output;
Creating an GZIPInputStream for the file
Reading TarInputStream...
Processing C:\AskulInstaller\Extracted Files\AskulInstaller\pid\Askul Logs\DbLayer_AskulMain_10_Apr_2013_07_44.log
java.io.FileNotFoundException: C:\AskulInstaller\Extracted Files\AskulInstaller\pid\Askul Logs\DbLayer_AskulMain_10_Apr_2013_07_44.log (The system cannot find the path specified)
C:\AskulInstaller\Extracted Files\AskulInstaller\pid\Askul Logs\DbLayer_AskulMain_10_Apr_2013_07_44.log (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:165)
at untargz.Untargz.untar(Untargz.java:37)
at untargz.Untargz.run(Untargz.java:55)
at untargz.Untargz.main(Untargz.java:64)
Is there a way I am supposed to place My directories so that the extraction Happens or what exactly is My Mistake?
If the tar file contains an entry for a file foo/bar.txt but doesn't contain a previous directory entry for foo/ then your code will be trying to create a file in a directory that doesn't exist. Try adding
destFile.getParentFile().mkdirs();
just before you create the FileOutputStream.
Alternatively, if you don't mind your code depending on Ant as a library then you can delegate the whole unpacking process to an Ant task rather than doing it by hand. Something like this (not fully tested):
Project p = new Project();
Untar ut = new Untar();
ut.setProject(p);
ut.setSrc(tarFile);
if(tarFile.getName().endsWith(".gz")) {
ut.setCompression((UntarCompressionMethod)EnumeratedAttribute.getInstance(UntarCompressionMethod.class, "gzip"));
}
ut.setDest(destDir);
ut.perform();

Java i18n without RessourceBundle

I am trying to get the i18n properties file out of my BuildPath. If you are trying to get the PropertiesFile the ResourceBundle.getBundlewill throw a java.util.MissingResourceException. Is there a method to load i18n files from outside the BuildPathbut still has the comfort of detecting your locale?
EDIT:
Here is the solution I was able to create with the Help of Paweł Dyda. Maybe somebody will need it. Probably there could be some improvements made, but it works ;)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle.Control;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
public class GlobalConfigurationProvider {
Logger logger = Logger.getLogger(GlobalConfigurationProvider.class);
private static GlobalConfigurationProvider instance;
PropertiesConfiguration i18n;
private GlobalConfigurationProvider() {
String path = GlobalConfigurationProvider.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = "";
try {
decodedPath = URLDecoder.decode(path, "UTF-8");
// This ugly thing is needed to get the correct
// Path
File f = new File(decodedPath);
f = f.getParentFile().getParentFile();
decodedPath = f.getAbsolutePath();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
this.logger.error("Failed to decode the Jar path", e);
}
this.logger.debug("The Path of the jar is: " + decodedPath);
String configFolder = FilenameUtils.concat(decodedPath, "cfg");
String i18nFolder = FilenameUtils.concat(configFolder, "i18n");
File i18nFile = null;
try {
i18nFile = this.getFileForLocation(new File(i18nFolder), Locale.getDefault());
} catch (FileNotFoundException e) {
e.printStackTrace();
this.logger.error("Can't find the LocaleFile", e);
}
if (!i18nFile.exists()) {
// If this can't be found something is wrong
i18nFile = new File(i18nFolder, "eng.i18n");
if (!i18nFile.exists()) {
this.logger.error("Can't find the i18n File at the Location: " + i18nFile.getAbsolutePath());
}
}
this.logger.debug("The Path to the i18n File is: " + i18nFile);
try {
this.i18n = new PropertiesConfiguration(i18nFile);
} catch (ConfigurationException e) {
this.logger.error("Couldn't Initialize the i18nPropertiesFile", e);
}
}
private File getFileForLocation(File i18nFolder, Locale locale) throws FileNotFoundException {
Control control = Control.getControl(Control.FORMAT_DEFAULT);
List<Locale> locales = control.getCandidateLocales(this.getBaseName(), locale);
File f = null;
for (Locale l : locales) {
String i18nBundleName = control.toBundleName(this.getBaseName(), l);
String i18nFileName = control.toResourceName(i18nBundleName, "properties");
f = new File(i18nFolder, i18nFileName);
this.logger.debug("Looking for the i18n File at: " + f);
if (f.exists()) {
return f;
}
}
// Last try for a File that should exist
if (!locale.equals(Locale.US)) {
return this.getFileForLocation(i18nFolder, Locale.US);
}
throw new FileNotFoundException("Can't find any i18n Files in the Folder " + i18nFolder.getAbsolutePath());
}
private String getBaseName() {
// TODO: Get this from the Settings later
return "messages";
}
public static GlobalConfigurationProvider getInstance() {
if (GlobalConfigurationProvider.instance == null) {
GlobalConfigurationProvider.instance = new GlobalConfigurationProvider();
}
return GlobalConfigurationProvider.instance;
}
public String getI18nString(String key) {
try {
return this.i18n.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
Of course there are methods to do that. Anyway, I believe your problem is the wrong path to the resource you are trying to load.
Nonetheless, for sure you are looking the way to use Locale fall-back mechanism to load very specific resource. It can be done. You may want to take a look at ResourceBundle.Control class. For example you can get the list of fall-back locales:
Control control = Control.getControl(Control.FORMAT_DEFAULT);
List<Locale> locales = control.getCandidateLocales("messages",
Locale.forLanguageTag("zh-TW"));
From there, you can actually create names of the resource files you are looking for:
for (Locale locale : locales) {
String bundleName = control.toBundleName("messages", locale);
String resourceName = control.toResourceName(bundleName, "properties");
// break if resource under given name exist
}
Then, you need to load the resource somehow - you may want to use ClassLoader's getResourceAsStream(String) to open the InputStream for you. The last step could be actually use the stream as an input to PropertyResourceBundle:
ResourceBundle bundle = new PropertyResourceBundle(inputStream);
You can alternatively pass a Reader rather than InputStream, which has at least one advantage - you may actually allow properties file to be encoded in UTF-8, rather than regular ISO8859-1.

Categories