What I have so far:
A block of code that intakes a username and password and write it to a textfile.
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
try {
FileWriter userInfoWriter = new FileWriter(usernameFilename);
BufferedWriter writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.write("\r\n" + writePassword);
writeToFile.close();
What I need to accomplish:
Create a directory to a pre-made folder called users.
Save the file to usernameFilename to a directory.
What I've tried:
I've searched online everywhere! I cant find anything to do this :c
Extra info:
Since all computers are different, I would like to use the .getAbsolutePath() method when creating the directory.
Take a look at:
java.io.File
File#exists
File#isDirectory
File#mkDirs
You could update your code to look more look this...
String usernameFilename;
usernameFilename = newUsernameField.getText();
char[] signupPassword = newPasswordField.getPassword();
String writePassword = new String(signupPassword);
File users = new File("users");
if ((users.exists() && users.isDirectory()) || users.mkdirs()) {
FileWriter userInfoWriter = null;
BufferedWriter writeToFile = null;
try {
userInfoWriter = new FileWriter(users.getPath() + File.seperator + usernameFilename);
writeToFile = new BufferedWriter(userInfoWriter);
writeToFile.write(usernameFilename);
writeToFile.newLine();
writeToFile.write(writePassword);
//....
} finally {
try {
writeToFile.close();
} catch (Exception exp) {
}
}
} else {
throw new IOException("Could not create/find Users directory");
}
Related
I have a set of words and an outside file.
I want to check if a word in the set is already present in the outside file. If the word is already in the file, then do nothing, if the word is not in the outside file already, then add it to the outside file.
This is the code I have written:
public static void toFile(Set<String> vocab, String filename)
{
try
{
for(String vocabWord : vocab)
{
File file = new File(filename);
Scanner sc2 = new Scanner(file);
while(sc2.hasNextLine())
{
String docWord = sc2.nextLine();
if (!(vocabWord.equals(docWord)))
{
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
else
break;
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
I am using three different text documents to test it, have the line "test file one", "test file two", and "test file three".
The output I was expecting was: "test file three" (it is connected with a stop list which one and two are part of, and has been working)
However, when I run it, either with only one of the files or all three consecutively, the file always comes out empty.
I tried changing up things in the method, but nothing has worked, I either get an infinite loop or nothing in the outside file.
I am not sure what I am missing... I would really appreciate any help.
I tried this and added some comments for explanation. I have tested on local machine and it works
public static void toFile(Set<String> vocab, String filename) {
try {
for(String vocabWord : vocab) {
//task for each String in our Set
File file = new File(filename);
Scanner sc2 = new Scanner(file);
boolean exists = false;//lets say it doesn't exist
while(sc2.hasNextLine()) {
//task for each line in the text
//search the whole file first for the word
String docWord = sc2.nextLine();
if (docWord.equals(vocabWord)){
exists = true;
break;
}
}
if (!exists) {
//add the vocabWord only if it doesnt exists
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
To append the missing vocabulary in order of vocab, you can reduce the file operations
as such:
public static void toFile(Set<String> vocab, String filename) {
try {
Charset charset = Charset.defaultCharset();
Path path = Paths.get(filename);
Set<String> existing = Files.lines(path, charset)
.collect(Collectors.toSet());
if (!existing.isEmpty()) {
try (BufferedWriter bw = Files.newBufferedWriter(path, charset,
StandardOpenOption.APPEND);
PrintWriter printWriter = new PrintWriter(bw)) {
vocab.stream()
.filter(word -> !existing.contains(word))
.forEach(word -> printWriter.println(word));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
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:
I am trying to replace a string from a js file which have content like this
........
minimumSupportedVersion: '1.1.0',
........
now 'm trying to replace the 1.1.0 with 1.1.1. My code is searching the text but not replacing. Can anyone help me with this. Thanks in advance.
public class replacestring {
public static void main(String[] args)throws Exception
{
try{
FileReader fr = new FileReader("G:/backup/default0/default.js");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine()) != null) {
if(line.contains("1.1.0"))
{
System.out.println("searched");
line.replace("1.1.0","1.1.1");
System.out.println("String replaced");
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
First, make sure you are assigning the result of the replace to something, otherwise it's lost, remember, String is immutable, it can't be changed...
line = line.replace("1.1.0","1.1.1");
Second, you will need to write the changes back to some file. I'd recommend that you create a temporary file, to which you can write each `line and when finished, delete the original file and rename the temporary file back into its place
Something like...
File original = new File("G:/backup/default0/default.js");
File tmp = new File("G:/backup/default0/tmpdefault.js");
boolean replace = false;
try (FileReader fr = new FileReader(original);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(tmp);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("1.1.0")) {
System.out.println("searched");
line = line.replace("1.1.0", "1.1.1");
bw.write(line);
bw.newLine();
System.out.println("String replaced");
}
}
replace = true;
} catch (Exception e) {
e.printStackTrace();
}
// Doing this here because I want the files to be closed!
if (replace) {
if (original.delete()) {
if (tmp.renameTo(original)) {
System.out.println("File was updated successfully");
} else {
System.err.println("Failed to rename " + tmp + " to " + original);
}
} else {
System.err.println("Failed to delete " + original);
}
}
for example.
You may also like to take a look at The try-with-resources Statement and make sure you are managing your resources properly
If you're working with Java 7 or above, use the new File I/O API (aka NIO) as
// Get the file path
Path jsFile = Paths.get("C:\\Users\\UserName\\Desktop\\file.js");
// Read all the contents
byte[] content = Files.readAllBytes(jsFile);
// Create a buffer
StringBuilder buffer = new StringBuilder(
new String(content, StandardCharsets.UTF_8)
);
// Search for version code
int pos = buffer.indexOf("1.1.0");
if (pos != -1) {
// Replace if found
buffer.replace(pos, pos + 5, "1.1.1");
// Overwrite with new contents
Files.write(jsFile,
buffer.toString().getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
}
I'm assuming your script file size doesn't cross into MBs; use buffered I/O classes otherwise.
Here is my code
private void edit(String search_bookname) {
String current_bookname ="", current_ISBN = "", current_author = "", current_rating = "", record = "", comma = ",", current_status = "";
int flag1 = 0, flag2 = 0;
File file = new File("Book_data.txt");
try {
BufferedReader reader = new BufferedReader (new FileReader (file));
File f = new File("Book_data_copy.txt");
FileWriter create = new FileWriter(f);
PrintWriter y = new PrintWriter(create);
while(reader.ready())
{
record = reader.readLine();
StringTokenizer st = new StringTokenizer(record, ",");
while(st.hasMoreTokens()) {
current_bookname = st.nextToken();
current_author = st.nextToken();
current_ISBN = st.nextToken();
current_rating = st.nextToken();
current_status = st.nextToken();
flag2 = 0;
if (search_bookname.equals(current_bookname)) {
flag1 = 1;
flag2 = 1;
try {
y.print(current_bookname); y.print(comma);
y.print(current_author); y.print(comma);
y.print(current_ISBN); y.print(comma);
y.print(current_rating); y.print(comma);
y.println("Borrowed");
} catch(Exception e) {}
Thread.sleep(1000);
}
}
if(flag2==0) // All non-matching records shall only be written to file. Record to be deleted will not be written to new file
{
y.print(current_bookname); y.print(comma); //One record per line..... Each field in a record is seperated by COMMA (" , " )
y.print(current_author); y.print(comma);
y.print(current_ISBN); y.print(comma);
y.print(current_rating);y.print(comma);
y.println(current_status);
}
}
reader.close();
y.close();
create.close();
} catch (Exception e) {}
if(flag1==1) //Rename File ONLY when record has been found for Edit
{
File oldFileName = new File("Book_data_copy.txt");
File newFileName = new File("Book_data.txt");
System.out.println("File renamed .....................");
try
{
newFileName.delete(); oldFileName.renameTo(newFileName);
if (oldFileName.renameTo(newFileName))
System.out.println("File renamed successfull !");
else
System.out.println("File rename operation failed !");
Thread.sleep(1000);
} catch (Exception e) {}
}
}
The project is for a library system. I am relatively new to java and I use netbeans on windows 8.1. The code outputs rename operation failed. Almost exactly the same code for edit has been used before in the program and it worked.
Any suggestions or code corrections would be helpfu.
Thanks!
Your issue is with the below code section
oldFileName.renameTo(newFileName);
if (oldFileName.renameTo(newFileName))
you are trying to rename twice. The first might pass but the 2nd will definitely fail. Check if the original file was renamed. If any error is thrown pring the stack trace and add the trace to your post.
You are trying to rename oldFileName twice:
newFileName.delete(); oldFileName.renameTo(newFileName); // rename
if (oldFileName.renameTo(newFileName)) // rename again ?!
System.out.println("File renamed successfull !");
else
System.out.println("File rename operation failed !");
The second rename in the if() fails, because the file was renamed already in the line before.
There are any number of problems here, starting with ignoring exceptions; not closing the file in a finally block; and using Reader.ready() incorrectly.
This is 2015. Use java.nio.file!
final Path srcFile = Paths.get("Book_data.txt").toAbsolutePath();
final Path dstFile = srcFile.resolveSibling("Book_data_copy.txt");
try (
final BufferedReader reader = Files.newBufferedReader(srcFile, StandardCharsets.UTF_8);
final BufferedWriter writer = Files.newBufferedWriter(dstFile, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
final PrintWriter pw = new PrintWriter(writer);
) {
// work with reader and pw
}
if (flag1 == 1)
Files.move(dstFile, srcFile, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
If you did that from the start, not only would your resources have been closed safely (your code doesn't do that) but you would have gotten a meaningful exception as well (you are trying to rename twice; you would have had a NoSuchFileException on the second rename).
Relying on File is an error, and it has always been.
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.