file existed or not by passing time - java

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.");
}
}

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");
}
}

Start and stop postgreSQL service through java code

I have one requirement where I need to start and stop postgreSQL service through java code. I have written below code but I am getting below error:
System error 5 has occurred.
Access is denied.
System error 5 has occurred.
Access is denied.
Below is my code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import common.core.Logger;
import frontend.guifx.util.ConstPG;
public class StartAndStopPostgres {
public static String version = "9.5";
public static void main(String[] args){
try {
System.out.println("Execution starts");
copyPostgreSqlConfFileAndRestartPg();
System.out.println("Execution finished");
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void copyPostgreSqlConfFileAndRestartPg() throws IOException, InterruptedException {
// TODO Auto-generated method stub
Path path = Paths.get("data/PGLogs");
//if directory exists?
if (!Files.exists(path)) {
try {
Files.createDirectories(path);
} catch (IOException e) {
//fail to create directory
e.printStackTrace();
}
}
Logger.print(StartAndStopPostgres.class, new String[] { "Copying postgresql.conf file ........" });
Path source = Paths.get("data/postgresql.windows.conf");
String copyConfFileTo = getInstallationPath(version);
copyConfFileTo = copyConfFileTo.substring(0, copyConfFileTo.lastIndexOf("\\"));
Path outputDirectoryPath = Paths.get(copyConfFileTo+File.separator+"data");
Files.copy(source, outputDirectoryPath.resolve(outputDirectoryPath.getFileSystem().getPath("postgresql.conf")), StandardCopyOption.REPLACE_EXISTING);
Logger.print(StartAndStopPostgres.class, new String[] { "Tunning datbase starts........" });
Runtime rt = Runtime.getRuntime();
final File file = new File(System.getProperty("java.io.tmpdir") + File.separator + ConstPG.CREATE_RESTART_PG_BAT_FILE);
PrintWriter writer = new PrintWriter(file, "UTF-8");
writer.println("net stop postgresql-x64-"+version);
writer.println("net start postgresql-x64-"+version);
writer.close();
String executeSqlCommand = file.getAbsolutePath();
Process process = rt.exec(executeSqlCommand);
/*final List<String> commands = new ArrayList<String>();
commands.add("cmd.exe");
commands.add("/C");
commands.add("net stop postgresql-x64-9.5");
commands.add("net start postgresql-x64-9.5");
ProcessBuilder b = new ProcessBuilder(commands);
Process process = b.start();*/
//public static final String PG_RESTART_PG_LOG_FILE = PG_LOGS+"/pgRestartProcess.log";
File createPgRestartProcessFile = new File(ConstPG.PG_RESTART_PG_LOG_FILE);
redirectProcessExecutionOutput(process, createPgRestartProcessFile);
int exitVal = process.waitFor();
Logger.print(StartAndStopPostgres.class, new String[] { "EXIT VALUE after tunning the PostgreSql database :::::::::::::::::::::" + exitVal + " Logs written to file at: " + createPgRestartProcessFile.getAbsolutePath() });
}
public static String getInstallationPath( String version) {
//public static final String PROGRAMME_FILES = "C:\\Program Files\\";
// public static final String PROGRAMME_FILES_X86 = "C:\\Program Files (x86)\\";
// public static final String POSTGRESQL = "PostgreSQL";
// public static final String PSQL_PATH = "\\bin\\psql.exe";
//Const values used below are as above
String psql = findFile(ConstPG.PROGRAMME_FILES, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
if (psql == null) {
psql = findFile(ConstPG.PROGRAMME_FILES_X86, ConstPG.POSTGRESQL + "\\" + version + ConstPG.PSQL_PATH);
}
if(psql != null){
psql = psql.substring(0, psql.lastIndexOf("\\"));
}
return psql;
}
public static String findFile(String directoryName, String fileName) {
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
String absolutePath;
if (fList != null) {
for (File file : fList) {
if (file.isFile()) {
absolutePath = file.getAbsolutePath();
if (absolutePath.contains(fileName))
return (absolutePath);
} else if (file.isDirectory()) {
absolutePath = findFile(file.getAbsolutePath(), fileName);
if (absolutePath != null)
return (absolutePath);
}
}
}
return (null);
}
private static void redirectProcessExecutionOutput(Process process, File processFile) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
FileWriter fw = new FileWriter(processFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((line = reader.readLine()) != null) {
Logger.print(StartAndStopPostgres.class, new String[] { line });
bw.write(line);
bw.newLine();
}
bw.close();
}
}
If I start my eclipse as an Administrator then this works fine. Also if I run start and stop commands on command prompt (which is opened as an Administrator i.e. right click on command prompt icon and click 'run as Administrator') then they execute successfully. But if I run the commands on normal command prompt (which is not opened as a administrator) then I get the same error there as well.
Please advise if there is any solution or any approach to solve this problem.
In java there is a option to run windows cmd as administrator
replace your code "commands.add("cmd.exe");" with below code and try
commands.add("runas /profile /user:ADMINUSERNAME \"cmd.exe");

setout file is not getting generated daily based on date

I have application which keeps listening on a port and if any request comes ,processes and sends the response back.I have redirected System.out.println of the program to a text file. I want the file to be rolledout everyday.But i don see a rollout at 12.00 am .Sometimes rollout happens and sometimes logs are appended on yesterday's file itself. Code snippet given below.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MBServ {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
String request_date = null;
String request_time = null;
String logFile="MBServ_";
ConnectServiceInfo fiServiceInfo = ConnectServiceInfo.getInstance();
ConnectServiceInfo fiservice = fiServiceInfo.getInstance();
try {
serverSocket = new ServerSocket(1122);
} catch (IOException e) {
System.exit(-1);
}
while (listening) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
request_date = sdf.format(date);
logFile="MBServ_"+request_date+".log";
System.setOut(new PrintStream(new FileOutputStream(logFile,true)));
new MBServT(serverSocket.accept(), fiservice).start();
}
serverSocket.close();
}
}
I think you have to force the creation of the file before using it.
Here's an exmaple :
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
request_date = sdf.format(date);
logFile="MBServ_"+request_date+".log";
File file = new File(logFile);
file.createNewFile();
...
Documentation : https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()

I am trying to generate 7z file using java exec utility but it will creating empty zip file

package com.otp.util;
import java.io.FileWriter; import java.io.IOException; import
java.text.SimpleDateFormat; import java.util.Date;
import com.otp.servlets.MessageServlet;
public class CDRWriter {
public FileWriter fileWriter = null;
static int lineCounter = 0;
static String fileName = null;
public void writeCDR(String cdrData) throws IOException {
if(lineCounter == 0){
fileName = createFile();
}else if(lineCounter>500){
String temp=fileName;
fileName = createFile();
lineCounter=0;
Runtime rt = Runtime.getRuntime();
String zipCmd="7z a "+"\""+MessageServlet.filePath+temp+".7z"+"\""+" "+"\""+MessageServlet.filePath+temp+"\"";
System.out.println("zipCmd = "+zipCmd);
rt.exec(zipCmd);
//rt.exec("del "+MessageServlet.filePath+temp);
}
System.out.println("cdr data = "+cdrData);
try {
if(lineCounter == 0){
fileWriter = new FileWriter(MessageServlet.filePath+fileName);
}else{
fileWriter = new FileWriter(MessageServlet.filePath+fileName,true);
}
System.out.println("cdr after if else condition ="+cdrData);
fileWriter.write(cdrData.toString());
System.out.println("cdr after write method ="+cdrData);
fileWriter.write("\r\n");
fileWriter.flush();
//fileWriter.close();
lineCounter++;
System.out.println("CDRWriter : lineCounter = "+lineCounter); } catch (IOException e) {
e.printStackTrace();
}
}// end of WriterCDR method
public String createFile() throws IOException {
SimpleDateFormat sdf = new
SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
String fileName ="GSMS_CDR_"+ sdf.format(new Date())+".txt" ;
return fileName;
}// end of the createFile method
}// end of CDRWriter class
I would do something like that:
import java.io.*;
import SevenZip.Compression.LZMA.*;
public class Create7Zip
{
public static void main(String[] args) throws Exception
{
// file to compress
File inputToCompress = new File(args[0]);
BufferedInputStream inputStream = new BufferedInputStream(new java.io.FileInputStream(inputToCompress));
// archive
File compressedOutput = new File(args[1] + ".7z");
BufferedOutputStream outputStream = new BufferedOutputStream(new java.io.FileOutputStream(compressedOutput));
Encoder encoder = new Encoder();
encoder.SetAlgorithm(2);
encoder.SetDictionarySize(8388608);
encoder.SetNumFastBytes(128);
encoder.SetMatchFinder(1);
encoder.SetLcLpPb(3,0,2);
encoder.SetEndMarkerMode(false);
encoder.WriteCoderProperties(outputStream);
long fileSize;
fileSize = inputToCompress.length();
for (int i = 0; i < 8; i++)
{
outputStream.write((int) (fileSize >>> (8 * i)) & 0xFF);
}
encoder.Code(inputStream, outputStream, -1, -1, null);
// free resources
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
The SKD for the SevenZip packages come from the offical SKD. Download it here ;).
Disclaimer: I believe, I found that snippet a while ago on the net...but I don't found the source anymore.

Writing in a text File in java

I wrote a very simple piece of code, It was working perfectly since yesterday but now not working and even after lots of research/debugging i have not got the issue
import java.net.InetAddress;
import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class DetectLoggedInUser{
public static void returnUserName()
{
String computerName;
try {
File file =new File("d:\\TestFolder\\UsersloggedIn.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content= "\n UserName="+System.getProperty("user.name")+ " || Date and Time= "+new Date();
bufferWritter.write(content);
bufferWritter.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[])
{
returnUserName();
}
}
Now file is created but nothing is being written in file
Is there anything wrong with this code(keeping in mind it was working since yesterday)?
Try this:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
public class DetectLoggedInUser {
public static void returnUserName() {
try {
File file = new File("d:\\TestFolder\\UsersloggedIn.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
String content = "\n UserName=" + System.getProperty("user.name")
+ " || Date and Time= " + new Date();
bufferWritter.write(content);
bufferWritter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String args[]) {
returnUserName();
}
}
You can use
FileWriter fileWritter = new FileWriter(file.getAbsolutePath(), true);
Instead of file.getName() in your code.File.getName() method returns only the name of the file or directory,not the absolute path;
You don't need to check if the files exists or not, beside that it works fine for me.

Categories