How to get the updated file text - java

I am making a JFrame from where the user will be able to insert new methods in the file. If the file is not there, program will create the new file and then insert the method there. If the file is already there, it will try to create the new method with the given name but if the file contains the method with the same name, it'll give user the alert.
I am able to do all these things properly, only problem is after creating the new method in the class file, if the user again click on the Create Method button, application does not throws any alert as it is unable to read the new method name from the file. When I check the file content, I can see the new method there but somehow my code is not able to read the new code from the file. Here is the code for the same.
File f = null;
f = new File(Report.path + "//src//_TestCases//" + tc_name + ".java");
if (!f.exists()) {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
f.createNewFile();
bw.write(testcase);
bw.close();
}
Class<?> c = Class.forName("_TestCases." + tc_name);
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().toLowerCase()
.equals(module_name.toLowerCase())) {
JOptionPane
.showMessageDialog(null,
"Module with the given name already exists. Please provide other name.");
return false;
}
}
List<String> lines = Files.readAllLines(f.toPath(),
StandardCharsets.UTF_8);
String text = "";
if (lines.contains(" #AfterClass")) {
text = " #AfterClass";
} else {
text = "#AfterClass";
}
lines.add(lines.indexOf(text), "#Test\npublic void " + module_name
+ "() throws Exception {\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
for (int i = 0; i < tc_values.size(); i++) {
lines.add(lines.indexOf(text), tc_values.get(i));
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
}
lines.add(lines.indexOf(text), "\n}\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);

Not sure what the issue was but when I changed the logic of getting the method name from the file, it worked for me. Used scanner to read the file contents and get the method name, earlier was using the below line to get the method name from the file.
Method[] m = c.getDeclaredMethods();

Related

Why does my anti-duplicate file loop not function?

I am creating a project where a random "UserID" is generated when the user wants to add a customer. Along with this UserID, a file is created with the formatted userID which contains user entered first name and last name. I am currently using random to generate user ID's, and created a do while loop to avoid possible duplicate. In the final project, I will have random set to pull from 9999, but for demonstration and duplicate testing purposes, it is set to 1.
All of the sudden, my do-while loop is not functioning as it has been. I have tried moving a few things around, checking syntax and changing directories, but nothing is working.
Why is my do-while loop that serves as an anti-duplicate file method not working?
public static void userAddition() throws IOException
{
boolean retry = true;
String formattedUserId = "";
Random randomNumbers = new Random();
int userId;
final int MAX_RETRIES = 10;
int retryCount = 0;
do
{
retryCount++;
userId = randomNumbers.nextInt(1);
formattedUserId = String.format("%04d", userId);
File f = new File("C:/Users/Nick/Desktop/Library" + formattedUserId + ".txt");
retry = f.exists();
}
while (retry && retryCount < MAX_RETRIES);
if (retry)
{
System.out.println("Error");
}
else
{
// happy path
String userFirstName = JOptionPane.showInputDialog("Enter the customer's first name:");
String userLastName = JOptionPane.showInputDialog("Enter the customer's last name:");
FileWriter fw = new FileWriter(formattedUserId + ".txt", true);
PrintWriter outputFile = new PrintWriter(fw);
outputFile.printf("#%s%n", formattedUserId);
outputFile.printf("%s %s", userFirstName, userLastName);
System.out.println(formattedUserId);
outputFile.close();
}
}
}
I expect the do-while loop to run through 10 times, before hitting the MAX_RETRIES and displaying "Error".
You test for the existence of file C:/Users/Nick/Desktop/Library0000.txt:
File f = new File("C:/Users/Nick/Desktop/Library" + formattedUserId + ".txt");
Then you create the file in the folder of the project with the name 0000.txt:
FileWriter fw = new FileWriter(formattedUserId + ".txt", true);
So your test for existence will never return true :)
The easy fix is to store the calculated file name in a variable:
String fileName = String.format("C:/Users/Nick/Desktop/Library/%04d.txt", userId);
File f = new File(fileName);
...
FileWriter fw = new FileWriter(fileName, true);
By the way, have a look at try-with-resources, you should use it like this:
try (Writer writer = new PrintWriter(FileWriter(fileName, true))) {
writer.printf("#%s%n", formattedUserId);
writer.printf("%s %s", userFirstName, userLastName);
// notice: no close(), this is handled automatically and better!
}

How to rename a txt file using Java after copying contents from another txt file

I have created a program where there is a file called groups.txt. This file contains a list of names. To delete a group, it has to exist within the file. I used the Scanner method to search through each line for the name. If it contains the line, it sets val as 1. Which triggers the val == 1 condition. What I wanted to do during this block, is try to delete groupName from the groups.txt file. To do this, I created a new txt file called TempFile which copies all the names from groups.txt EXCEPT groupName. This file is then renamed to groups.txt and the old groups.txt file is deleted.
Everything works as intended, except the renaming. The temp.txt file still exists and the groups.txt file is unchanged. I checked the boolean success, and it always returns as false. Any ideas how to solve this?
if (method.equals("delete group")){
int val = 0;
String groupName = myClient.readLine();
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
val = 1;
}
}
if (val == 1){
try {
File groupFile = new File("groups.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(groupFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
System.out.println(groupName);
while ((currentLine = reader.readLine()) != null){
String trimLine = currentLine.trim();
if (trimLine.equals(groupName)){
continue;
} else {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
groupFile.delete();
boolean success = tempFile.renameTo("groups.txt");
} catch (IOException f){
System.err.println("File Not Found: " + f.getMessage());
} }
} catch (FileNotFoundException f){
System.err.println("File Not Found Exception: " + f.getMessage());
}
}
CODE BEFORE THE ABOVE:
if (command.equals("group")){
String method = myClient.readLine();
if (method.equals("create group")){
String groupName = myClient.readLine();
int val = 0;
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
Report.error("group name already exists, please pick another");
val = 1;
}
}
} catch (FileNotFoundException f){
System.err.println("File Not Found: " + f.getMessage());
}
if (val == 0){
try {
PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
out.println(groupName);
out.close();
} catch (IOException e){
Report.error("IOException: " + e.getMessage());
}
}
In the second part of the code, this is where I originally update the groups.txt file. So every time the user adds a group, it updates the groups.txt file by adding the new groupName to the end of the file. First, I make sure the groupName doesn't already exist using Scanner. myClient is a BufferedReader which reads from another class which stores what the user types in the command line.
Also do not forget to close Scanner. First you should make delete() work and make sure you know your current working directory, and write your filepath relative to it. Check with:
File file = new File("abc.txt");
System.out.println(file.getAbsolutePath());
One thing might be unrelated, also check your environment because
In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case. The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

Reading multiple text files java

I'm having trouble on reading multiple text files to fit into one scanner for example I have multiple text files that are named text1.txt, text2.txt etc... I'm trying to make it so that once the user enters which text file number they want it will bring up that data via arrays.
File txt = new File("text.txt");
void readTextFiles() throws IOException {
String line[] = new String[100];
Scanner readTextFiles= new Scanner(txt);
while (readTextFiles.hasNextLine()) {
line[q] = readTextFiles.nextLine();
if (line[q].trim() != "") {
String item[] = line[i].split(" ");
time[q] = item[0];
date[q] = item[1];
}
q++;
}
readTextFiles.close();
}
my logic works like this but its a code error:
File txt= new File("txt" + textFileNumber + ".txt");
int textFileNumber=0;`
If I understood correctly, the error you got is because the initialisation of the local variable does not precede it's use. You need to declare the textFileNumber before its usage in the string concatenation.
Further you are implementing this functionality as a method. So why not make the file number a method parameter?
public void readTextFiles(int fileNumber){
File txtFile = new File("text" + fileNumber + ".txt");
//logic
}

Trying to write to a .DAT file but doesn't seem to be doing anything?

I used this code in a different application to write a name and highscore onto the file for my game. Now i'm using this code to get a name and password from a .DAT file and be able to add a new user and password. Here's the .DAT file.
michael123
speaker123
katherine123
motor123
username
password
Here's the code. Reading the file works fine but writing to it does nothing at all and i'm unsure why.
InputStream file;
BufferedReader fileStream;
FileWriter fileWriter;
BufferedWriter fileWrite;
String temp = "";
int users = 0;
public void readUserInfo() throws IOException {
try {
file = Board.class.getResourceAsStream("users.DAT");
fileStream = new BufferedReader(new InputStreamReader(file));
} catch (Exception e) {
System.out.println("File not found");
}
for (int i = 0; i < users; i++) {
temp = fileStream.readLine();
Board.username[i] = temp.trim();
temp = fileStream.readLine();
Board.password[i] = temp.trim();
}
//Close
fileStream.close();
file.close();
}
public void addUser() throws IOException {
fileWriter = new FileWriter(Board.class.getResource("users.DAT").getFile(),true);
fileWrite = new BufferedWriter(fileWriter);
System.out.println("Users : " + users);
//Skip already created users
for (int i = 0; i < users; i++) {
fileWrite.newLine();
fileWrite.append(Board.username[i]);
fileWrite.newLine();
fileWrite.append(Board.password[i]);
}
System.out.println("Adding" + Board.username[users] + " : " + Board.password[users]);
//Add user
fileWrite.newLine();
fileWrite.append(Board.username[users]);
fileWrite.newLine();
fileWrite.append(Board.password[users]);
//Close
fileWrite.close();
System.out.println("Closed fileWrite");
}
I'm using netbeans. The file being read from is in the same package as all the other classes.
Maybe you have packaged your jar with some state of the file users.DAT (a defined set of users) and when you read them from classpath you see only the users from the time you have created the jar. The writing goes then to another file.
You should read the user from the filesystem too.
Check the working directory of your app there should be correct file containing the users added.
Also no need for copying all the user over and over again every time you add one, just open your file in append mode
fileWriter = new FileWriter(new File("users.DAT"), true);
Unless you want to be able to delete users, in that case keep everything in memory and save when you exit the program or explicitly with a save action.
In your reading you use file = Board.class.getResourceAsStream("users.DAT"); in your writing you just create a file new File("users.DAT") what about changing your addUser() to
public void addUser() throws IOException {
fileWriter = new FileWriter(Board.class.getResource("users.DAT").getFile());
....
}
Edit: The problem is that during writing you are not retrieving the same file as before. I would add this method
public File getUserDataFile() {
return new File(Board.class.getResource("").getFile(), "users.DATA");
}
// then use it like this
new FileWriter(getUserDataFile());
// and
new BufferedReader(new InputStreamReader(getUserDataFile()));
then access it whenever you want to read and write to your file. The problem is Board.class.getResourceAsStream("users.DAT") will return null if your file doesnt exist.

Are these two ways of creating files, the same?

I was writing a program in Java to search for a piece of text
I took these 3 as inputs
The directory, from where the search should start
The text to be searched for
Should the search must be recursive (to or not to include the directories inside a directory)
Here is my code
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File file = new File(dirToSearch);
String[] fileNames = file.list();
for(int j=0; j<fileNames.length; j++)
{
File anotherFile = new File(fileNames[j]);
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
When recursion is set true, the program returns a FILENOTFOUNDEXCEPTION
So, I referred to the site from where I got the idea to implement this program and edited my program a bit. This is how it goes
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File[] files = new File(dirToSearch).listFiles();
for(int j=0; j<files.length; j++)
{
File anotherFile = files[j];
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
It worked perfectly then. The only difference between the two snippets is the way of creating the files, but they look the same to me!!
Can anyone point me out where I messed up?
In the second example it is used listFiles() whichs returns files. In your example it is used list() which returns only the names of the files - here the error.
The problem in the first example is in the fact that file.list() returns an array of file NAMES, not paths. If you want to fix it, simply pass file as an argument when creating the file, so that it's used as the parent file:
File anotherFile = new File(file, fileNames[j]);
Now it assumes that anotherFile is in the directory represented by file, which should work.
You need to include the base directory when you build the File object as #fivedigit points out.
File dir = new File(dirToSearch);
for(String fileName : file.list()) {
File anotherDirAndFile = new File(dir, fileName);
I would close your files when you are finished and I would avoid using throws Exception.

Categories

Resources