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");
}
}
Related
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.
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.
i am trying to code for a new file existed in folder or not by passing specific time stamp through javacode but i am not getting it ..can u help...
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");
package com.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class trst {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
boolean b = false;
File file, file1;
Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("MMddyyyyhhmmss");
String folder_name="backup_"+ft.format(today);
file = new File("./"+folder_name);
if (!file.exists())
{
b = file.mkdirs();
}
file1 = new File(file+"/"+"Test");
FileWriter fileWriter = new FileWriter(file1);
fileWriter.write("abc");
fileWriter.flush();
fileWriter.close();
if (b)
System.out.println("Backup has been created.");
else
System.out.println("Failed to create backup.");
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is my first post here and I hope to find some help as I#m not only new to this site but also to Java.
For a game I am using Properties (with a corresponding file) to save and load settings.
I also have written a language system where I now get problems (Explained under the code)
Language class: Lang.java :
package de.cozmic.phaseone.reference;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import de.cozmic.phaseone.PhaseOne;
import de.cozmic.phaseone.console.Console;
public class Lang {
private static String path = null;
public static final String en = "en";
public static final String de = "de";
public static final String it = "it";
public static final String fr = "fr";
public static Properties lang = new Properties();
public Lang() {
String language = PhaseOne.settings.getProperty("Language");
//language = de; //FOR TESTING
Console.addLine("Starting Language : " + language);
if (language == en) path = "en.l";
if (language == de) path = "de.l";
if (language == it) path = "it.l";
if (language == fr) path = "fr.l";
Console.addLine("First Tried Language Path : " + path);
if (path == null) path = "en.l";
Console.addLine("Final Language Path : " + path);
try {
InputStream in = Lang.class.getResourceAsStream(path);
lang.load(in);
in.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
e.printStackTrace();
}
}
public static void use(String language) {
try {
FileInputStream in = new FileInputStream(language);
lang.load(in);
in.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
e.printStackTrace();
}
reload();
}
private static void reload() {
//TODO
}
}
Main class: PhaseOne.java
package de.cozmic.phaseone;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import de.cozmic.phaseone.console.Console;
import de.cozmic.phaseone.console.Log;
import de.cozmic.phaseone.display.FLauncher;
import de.cozmic.phaseone.input.InputHandler;
import de.cozmic.phaseone.reference.Lang;
import de.cozmic.phaseone.reference.Reference;
public class PhaseOne {
public static Properties settings = new Properties();
public PhaseOne() {
new Log();
new InputHandler();
loadSettings();
new Lang();
new FLauncher();
}
private void loadSettings() {
File f = new File("settings.p");
if (!f.exists())
try {
f.createNewFile();
FileOutputStream out = new FileOutputStream(f.getAbsolutePath());
settings.setProperty("Language", Lang.en);
settings.setProperty("GameWidth", String.valueOf(Reference.WIDTH));
settings.setProperty("GameHeight", String.valueOf(Reference.HEIGHT));
settings.store(out, null);
out.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
e.printStackTrace();
}
try {
Console.addLine("Loading settings");
FileInputStream in = new FileInputStream(f.getAbsolutePath());
settings.load(in);
in.close();
} catch (IOException e) {
Console.addLine(e.getMessage());
Console.addLine("Error: Loading settings failed!");
e.printStackTrace();
}
Console.addLine("Loaded settings:");
Enumeration<?> enu = settings.propertyNames();
while (enu.hasMoreElements()) {
String set = (String) enu.nextElement();
Console.addLine(set + " : " + settings.getProperty(set));
}
}
public static void changeSettings(String setting, String value) {
settings.setProperty(setting, value);
}
public static void main(String[] args) {
new PhaseOne();
}
}
Basically everything is working correctly and the properties are used correctly to display the text.
The problem is that it works as long as I directly use a String variable containing "de", but nut if I let the program read the same (!) value "de" from the properties. In the Lang() Constructer it gets null for the path whereas when I used "de" for the language variable it worked correctly.
This is the settings.p:
#Thu Aug 14 23:33:31 CEST 2014
GameWidth=800
GameHeight=600
Language=de
And this is (the relevant part of) the Log file:
Loading settings
Loaded settings:
Language : de
GameWidth : 800
GameHeight : 600
Starting Language : de
First Tried Language Path : null
Final Language Path : en.l
I hope anyone can tell me what is wrong or give a suggestion what to try to get it working.
I looked over it several times and really don't see why it should be behaving like this.
Also in the log you can clearly see that the variable language actually is right, just the if statement doesn't recognize it for whatever reason.
Like I said when I directly give it the String value everything works as intended.
Thanks in advance for everyone who is reading this!
Strings are objects, and as such should not be compared for contents using ==. == is only for reference equality. Rewrite your block as:
if (en.equals(language)){
or better yet, with a switch statement:
switch(language){
case "en":
path = "en.l";
break;
case "de":
path = "de.l";
break;
// More cases...
default:
// handle invalid language error case
}
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.