(Hello world level tester here)
I've got a java application to delete a bunch of files post tests to keep everything clean, however the issue is I can't seem to get it to work, this is my first time touching on an array and it's a slightly more complex one than the ones they show in the tutorials, any assistance would be greatly appreciated.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
File filePath = new File(home+fileArray);
System.out.println(filePath);
for (String count: fileArray) {
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(count);
}
You should concat new file path for every element in an array, so need to put work with a file in for body. So in every iteration, you get in variable filePath next element of an array and then you need to concat this variable to base path home + filePath. Now you are looking at needed file, you can create file object and work with it.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
for (String filePath: fileArray) {
File file = new File(home + filePath);
System.out.println(filePath);
if (file.exists()) {
file.delete();
System.out.println("Deleted");
} else {
System.out.println("failed");
Assert.fail();
}
}
Seem like you expect that in variable count you will see a number of iterated files. In this case, it does not work like this. Such form of for acting like this: for (String arrayElement : arrayToWorkWith) - mean that on every iteration in variable arrayElement will be put next element from array arrayToWorkWith. If you need to count number of element during iterations you can introduce separate variable and increment it or use another form of for cycle - for (int i = 0; i < fileArray.length; i++).
try it this way
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
//File filePath = new File(home+fileArray); thats wrong here and will give you a invalid file anyway as you concatenating a string with an object
for (String file: fileArray) {
File filePath = new File(home+file); //here you need to define the file
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(file);
}
Related
I read this question here How to create a file in a directory in java?
I have a method that creates a QR Code. The method is called several times, depends on user input.
This is a code snippet:
String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);
The problem: If the user types "2" then this method will be triggered twice.
As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.
How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png
My idea:
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Any tips?
EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.
You can create more files eg. like follows
int totalCount = 0; //userinput
String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";
for(int counter = 0; counter < totalCount; counter++){
int size = 250;
//tbd
File myFile = new File(filePath+fileName+counter+"."+fileType);
/*
will result into files qrCODE0.png, qrCODE1.png, etc..
created at the given location
*/
}
Btw to add check if file exists is also good point.
{...}
if(!myFile.exists()){
//file creation
myFile.createNewFile()
}else{
//file already exists
}
{...}
Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.
int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";
String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);
You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file
if(myFile.exists()){
filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
myFile = new File(filePath);
}
createFile(myFile);
And you're done!
You can check /Users/Test direcroty before create file.
String dir = "/Users/Test";
String pngFileName = "qrCode";
long count = Files.list(Paths.get(dir)) // get all files from dir
.filter(path -> path.getFileName().toString().startsWith(pngFileName)) // check how many starts with "qrCode"
.count();
pngFileName = pngFileName + "(" + count + ")";
One class of my GUI has a variable for the file name. I want to pass this to another class so that I can process a file without having to hard code the file's name every time. The program compiles fine but I can't seem to run it correctly.
public void run() {
WordsCounter2 fileName = new WordsCounter2();
essayName = fileName.getFileList();
File f = new File(essayName);
//other code
WordsCounter2 is the class that houses the variable fileName, I'm calling it from this class and assigning it as the file's name, but this doesn't work. Could someone help?
if (rVal == JFileChooser.APPROVE_OPTION) {
File[] selectedFile = fileChooser.getSelectedFiles();
fileList = "nothing";
if (selectedFile.length > 0)
fileList = selectedFile[0].getName();
for (int i = 1; i < selectedFile.length; i++) {
fileList += ", " + selectedFile[i].getName();
}
statusBar.setText("You chose " + fileList);
}
else {
statusBar.setText("You didn't choose a file.");
}
fileList isn't empty because I have a label on the GUI that lists whatever file I chose.
Here's my new edit: now the exception occurs at the last line with the scanner and throws a NPE. Can you help?
public void run() {
WordsCounter2 pathNamesList = new WordsCounter2();
essayName = pathNamesList.getPathNamesList();
essayTitle = new String[essayName.size()];
essayTitle = essayName.toArray(essayTitle);
for (int i = 0; i < essayTitle.length; i++) {
f = new File(essayTitle[i]);
}
try {
Scanner scanner = new Scanner(f);
Your code is failing because File will not accept comma separated file names, in fact, it needs a single file path to create the file in the mentioned path. See here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html
You'll have to get complete paths in an array and put the file creation statement as follows:
File f;
for (int i=0; i<fileList.length; i++)
f = new File(fileList[i]);
where fileList is a String array holding the list of pathnames.
In case you're trying to write some content to these files as well, this should be helpful: Trying to Write Multiple Files at Once - Java
I'd like to create a file object as follows
File file = new File("MyFile-abcdfg.txt");
where the string between - and . is random and always changing. The length is also not the same.
I want to check the file.exist(), but the problem is I am not sure what will be the name of the file, as it keeps on changing.
You can find the Possible solution over here.
List of files starting with a particular letter in java
Thanks
You can create a String variable for example like this:
String dynamicPartOfFileName = "abcdfg";
If you want to you can replace the literal "abcdfg" by any other mechanism (such as generating a randomized String).
And use it as part of the filename like this:
File file = new File("MyFile-" + dynamicPartOfFileName + ".txt");
The +-operator will join the Strings together. Afterwards the new File()-constructor will use the joined String.
You can use random numbers to randomly pick values from your possible file names.
Random rand = new Random();
int randomNumber = rand.nextInt(2); // 0-1.
String s1 = "-";
if(randomNumber == 0){
s1 = "_";
}
int nameLength = rand.nextInt(100); //0-99
String characters = "";
String possibleCharacters = "abcdefg";
for(int i = 0; i < nameLength; i++){
characters += possibleCharacters[rand.nextInt(possibleCharacters.length)];
}
String filename = "MyFile" + s1 + characters + ".txt";
File file = new File(filename);
if(file.exists() && !file.isDirectory()) {
// do something
}
As far as I can tell, your problem is not how to create the file name, but rather, how to check if a file with that possible name exists.
If you know the formation rule for the names (suppose "aBeginning" + "aDatePresentation" + "anEnd"), then you can test for possible files, such as
boolean checkFileToday(){
Date today = new Date();
String name = "aBeginning"+today.getDate()+"anEnd";
File file = new File(name);
return file.exists();
}
The following code, generates new file with the unique name.
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class DynamicFile {
public static void main(String[] args) throws IOException {
int i = 4;
do {
//UUID creates random string.
String randomID = UUID.randomUUID().toString();
File file = new File("A:/NewFolder/MyFile-" + randomID.substring(0, 5) + ".txt");
file.createNewFile();
} while (i-- > 0);
}
}
Will create files like:
MyFile-1d2ef.txt
I currently have a big folder full of filenames in the format:
EXA_0100_01012014.csv
EXA_0114_11012014.csv
Always the same 3 letters at the start. I need to change all of these filenames so that they are in the format:
EXA_B_0100_01012014
So it's just a case of inserting an _B (always _B) after the first three letters. I'm only just started learning Java so my attempts so far are fairly limited:
File oldfile = new File("EXA_0100_01012014.csv");
File newfile = new File("EXA_B_0100_01012014.csv");
I just need to do this for a large number of files all with the same 3 letter prefix. All the numbers change from file to file though.
If someone could give me a nudge in the right direction it would be much appreciated.
Thanks.
Use substring.
String fileName = "EXA_0100_01012014";
String newFileName = fileName.substring(0, 3) + "_B_" + fileName.substring(4);
Returns newFileName as:
EXA_B_0100_01012014
My suggestion:
String newFilename = oldfile.getFileName().replace("EXA_", "EXA_B_");
oldfile.renameTo(new File(newFilename));
If you don't like the replace() approach you could use the substring() method instead.
String oldFilename = oldfile.getFileName();
String newFilename = oldFilename.substring(0, 3) + "_B_" + oldFilename.substring(4);
oldfile.renameTo(new File(newFilename));
Here is the results from a quick google bomb:
First start looking at the renaming a file, Then you can instert a string by breaking the substrings apart and the prepending the first 3 characters and appending the rest after "_B". Similar to this.
public static void main(String[] h) {
final File folder = new File("/home/you/Desktop");
renameFilesForFolder(folder);
}
public static void renameFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
renameFilesForFolder(fileEntry);
} else {
if (fileEntry.getName().startsWith("EXA")) {
fileEntry.renameTo(new File(fileEntry.getName().replaceAll("(EXA)(_)", "$1_B$2")));
}
}
}
}
Here is a possible solution.
I used the following links to help me:
Nagesh Chauhan's solution for file renaming
http://www.beingjavaguys.com/2013/08/create-delete-rename-file-in-java.html
Philip Reichart's solution on file list
How to get contents of a folder and put into an ArrayList
import java.io.File;
import java.io.IOException;
public class RenameFiles
{
public RenameFiles()
{
File f = new File ("C:/work/play/java/list");
File[] list = f.listFiles();
for (int inum = 0; inum < list.length; inum++)
{
File curf = list[inum];
RenameFile(curf);
}
}
public void RenameFile(File curf)
{
String strfilename = curf.getAbsolutePath();
StringBuffer buf = new StringBuffer(strfilename);
int index = buf.indexOf("EXA_");
buf.insert(index+4, "B_");
String strnewfilename = buf.toString();
strnewfilename = strnewfilename.replace('\\', '/');
System.out.println(strnewfilename);
File newFileName = new File(strnewfilename);
try {
if (curf.renameTo(newFileName)) {
System.out.println("File "+strfilename+"renamed to "+strnewfilename+" successful !");
} else {
System.out.println("File "+strfilename+"renamed to "+strnewfilename+" failed !");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
RenameFiles fobj = new RenameFiles();
}
}
So I have the following code (which has been shamelessly copied from a tutorial so I can get the basics sorted), in which it asks the player to load their game (text-based adventure game)
but I need a way to display all the saved games in the directory. I can get the current directory no worries. Here is my code:
public void load(Player p){
Sleep s = new Sleep();
long l = 3000;
Scanner i = new Scanner(System.in);
System.out.println("Enter the name of the file you wish to load: ");
String username = i.next();
File f = new File(username +".txt");
if(f.exists()) {
System.out.println("File found! Loading game....");
try {
//information to be read and stored
String name;
String pet;
boolean haspet;
//Read information that's in text file
BufferedReader reader = new BufferedReader(new FileReader(f));
name = reader.readLine();
pet = reader.readLine();
haspet = Boolean.parseBoolean(reader.readLine());
reader.close();
//Set info
Player.setUsername(name);
Player.setPetName(pet);
Player.setHasPet(haspet);
//Read the info to player
System.out.println("Username: "+ p.getUsername());
s.Delay(l);
System.out.println("Pet name: "+ p.getPetName());
s.Delay(l);
System.out.println("Has a pet: "+ p.isHasPet());
} catch(Exception e){
e.printStackTrace();
}
}
}
File currentDirectory = new File(currentDirectoryPath);
File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
You can first get a File object for the directory:
File ourDir = new File("/foo/bar/baz/qux/");
Then by checking ourDir.isDirectory() you can make sure you don't accidentally try to work on a file. You can handle this by falling back to another name, or throwing an exception.
Then, you can get an array of File objects:
File[] dirList = ourDir.listFiles();
Now, you may iterate through them using getName() for each and do whatever you need.
For example:
ArrayList<String> fileNames=new ArrayList<>();
for (int i = 0; i < dirList.length; i++) {
String curName=dirList[i].getName();
if(curName.endsWith(".txt"){
fileNames.add(curName);
}
}
This should work:
File folder = new File("path/to/txt/folder");
File[] files = folder.listFiles();
File[] txtFiles = new File[files.length];
int count = 0;
for(File file : files) {
if(file.getAbsolutePath().endsWith(".txt")) {
txtFiles[count] = file;
count++;
}
}
It should be pretty self explanatory, you just need to know folder.listFiles().
To trim down the txtFiles[] array use Array.copyOf.
File[] finalFiles = Array.copyOf(txtFiles, count);
From the docs:
Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.