I wrote a short script to create a file to my Desktop, and the file appeared. I just did it all in main, like so:
import java.io.*;
import java.util.Scanner;
public class FilePractice {
public static void main(String[] args) {
//create a new File object
File myFile = new File("/home/christopher/Desktop/myFile");
try{
System.out.println("Would you like to create a new file? Y or N: ");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y"))
{
myFile.createNewFile();
}
else
{
//do nothing
}
}catch(IOException e) {
System.out.println("Error while creating file " + e);
}
System.out.println("'myFile' " + myFile.getPath() + " created.");
}
}
I just wanted to make sure the code worked, which it did. After that, I wanted to expand by creating a file with user input, as well as define which directory the user wished to send the file to. I'm on a Linux machine, and I wanted to send it to my Desktop again, so my user input was "/home/christopher/Desktop" for the userPath. Nothing happened. I even cd'd to my Desktop via terminal to "ls" everything there, and still nothing.
Perhaps my syntax is wrong?
If this is a duplicate of anything, my apologies. I tried to do a thorough search before coming here, but I only found info on creating files and sending files to directories that are already defined as a string (e.g. File myFile = new File("/home/User/Desktop/myFileName")).
Here is the expanded attempt:
try {
System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?");
String fileName = input.nextLine();
input.nextLine();
System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\");
String userFilePath = input.nextLine();
File userFile = new File(userFilePath, fileName);
System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: ");
String userChoice = input.nextLine();
if (userChoice.equalsIgnoreCase("Y")) {
userFile.createNewFile();
//print for debug
System.out.println(userFile.getPath());
}
}catch(IOException e) {
System.out.println("Error while attempting to create file " + e);
}
System.out.println("File created successfully");
My print statement for a debug attempt outputs "/home/christopher/Desktop", but not the file name appended to the directory.
Thanks for any help offered. This is just for experimentation while learning Java I/O. Since a hypothetical user may not be on the same OS as me, I can work on those methods later. I'm keeping it on my home machine, hence the Unix filepath names.
Changing input.nextLine() to input.next() solved the problem. The program was not reaching the if statement after asking the user if they were sure their entered path was the desired save point.
I also put in a simple else statement that printed out ("File not created") to verify that it was skipping it.
Anyway, question answered. :-)
Related
I am trying to create an authentication system of sorts that uses a file called Users.dat to store user data. Currently, I am developing a method to remove users by rewriting the Users.dat file, omitting the user specified. The code below works in a basic environment with an all-encompassing directory containing the .java files and the Users.dat file in the same spot. The old Users.dat file is deleted and Users.dat.tmp is renamed to User.dat. (No problems here, everything works as intended).
public static boolean RemoveUser(String userName) {
// TODO remove username from Users.dat
try {
File originalFile = new File("Users.dat");
System.out.println(originalFile.getAbsolutePath());
BufferedReader read = new BufferedReader(new FileReader("Users.dat"));
String line = null;
while ((line = read.readLine()) != null) {
if (line.indexOf(userName) != -1) {
break;
}
}
String[] userInfo = line.split(", ");
if (!userName.equals(userInfo[2])) {
System.out.println("Username not found. No users removed.");
read.close();
return false;
}
File tempFile = new File(originalFile.getAbsolutePath() + ".tmp");
PrintWriter print = new PrintWriter(new FileWriter(tempFile));
String lineToRemove = line;
BufferedReader read2 = new BufferedReader(new FileReader("Users.dat"));
while ((line = read2.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
print.println(line);
print.flush();
}
}
print.close();
read.close();
read2.close();
System.out.println(originalFile.getAbsolutePath());
originalFile.delete(); //This line is not executing correctly
tempFile.renameTo(originalFile); //Nor is this line
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return true;
}
Users.dat file format:
Joe, Last, jlast, 58c536ed8facc2c2a293a18a48e3e120, true
Sam, sone, samsone, 2c2a293a18a48e3e12058c536ed8facc, false
Jane, Best, jbest, 293a18a48e3e12052058c536ed8facc2c, false
Andrew, Estes, Aestes, 63a490d69aa544fd1272a976014ad570, true
Test, User, tuser, 63a490d69aa544fd1272a976014ad570, true
I have two System.out.println(originalFile.getAbsolutePath()) statements, one at the beginning, one at the end to make sure the path isn't getting screwed up in the process of everything somehow.
Like I said, the code works, however, when I try to implement it in my project, it creates the Users.dat.tmp and it writes the correct data to it, but it does not delete the old Users.dat file, nor does it rename the Users.dat.tmp file to replace Users.dat. I'm certain the directory is correct, as I am literally displaying it as the code executes. I can't figure out any other reason why originalFile.delete() and tempFile.renameTo(originalFile) aren't functioning properly.
EDIT:
Using java.nio.file, I was able to produce an error message. it reads:
java.nio.file.FileSystemException: C:\Path\Users.dat: The process cannot access the file because it is being used by another process.
I don't have the file open when this error message is shown, and I don't get this error using java.nio in my testing environment mentioned at the beginning. I'm not sure what other process the message is referring to.
EDIT 2:
I tried running the code on other machines, one a Mac, the other a Windows laptop, and the code functioned on the Mac just fine, but I was still seeing the same issue on the Windows laptop.
I had the similar issue. My problem was not closing all the streams I read and written to the file. Thanks for your Edit #1, that was helpful
When you wrap
BufferedReader read = new BufferedReader(new FileReader("Users.dat"));
don't you need to close the inner readers too?
If not for the author, but for those who stambled upon this question (like me), hope this suggestion will be useful
I had an earlier function that I was calling in main that was accessing Users.dat, but I never closed the BufferredReader in that function.
Here is my code: https://pastebin.com/1Cmg5Rt8
The program asks the user for their name.
It then generates random math problems, and counts correct answers and incorrect answers.
The user is rewarded $0.05 for correct answers and penalized $0.03 for incorrect answers.
All of the above has been done.
I am stuck starting from here:
A file is created using their name.
The amount of answers they got correct/incorrect are recorded to a text file.
If a file under their name already exists, I must combine their results with the results of the ones on the file.
Example of existing text file:
Correct answers: 1
Incorrect answers: 0
Earnings: $0.05
If the user runs the program again and gets 1 correct answer, it must be updated like this:
Correct answers: 2
Incorrect answers: 0
Earnings: $0.10
Currently, instead of updating, it is being overwritten.
If I choose show stats at the beginning, this is the result (it uses the initialized values):
Correct answers:0
Incorrect answers: 0
Earnings: $0.00
I have spent hours trying to figure this out. I refuse to sleep until I solve this. Someone please help me. I will greatly appreciate it.
You need to read the name in /before/ you retrieve the stats, i.e. your main method should look like this:
public static void main(String[] args) {
validateCreditsResponse();
name();
retrieveStats();
menu();
saveStats();
}
Also, in this method, you need to also output a println like you do in the 'else' branch:
if (money > 0) {
outputfile.printf("Earnings: $%.2f", money);
// Add outputfile.println();
}
Finally, in this method you need to read in the data:
//Creates new text file for the user unless one already exists.
public static void retrieveStats() {
try {
writer = new FileWriter(userName + "Stats.txt", true);
outputfile = new PrintWriter (writer);
} catch (IOException e) {
}
}
You would start doing this with a FileReader, rather than a FileWriter.
For example in Java 8, like this:
//Reads existing text file for the user.
public static void retrieveStats() {
try (BufferedReader br = new BufferedReader(new FileReader(userName + "Stats.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher correctMatcher = Pattern.compile("Correct Answers:(.*)").matcher(line);
if (correctMatcher.matches()) {
correct = Integer.valueOf(correctMatcher.group(1));
}
// TODO complete other matchers
}
} catch (IOException e) {
}
}
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 7 years ago.
Hey Stack Overflow people, I'm having a bit of trouble understanding how writing and appending files works. Here is what I've been asked to do
• Save (append) the data for the contract to the text-based summary file (contracts.txt).
Each line in the file must hold the details for a single contract with the following information separated by spaces or tabs:
• Contract Date (today’s date - see technical details for format).
• Package (1=Small, 2=Medium and 3=Large)
• Data Bundle (1=Low, 2=Medium, 3=High and 4=Unlimited).
• Period in Months
• Allow international call from package minutes (Y or N)
• Reference Number.
• Monthly Charge (in pence).
• Client Name.
An example of the sort of file I'm looking to write would be this.
So far I have this code
public void appendFile()
{
PrintWriter output = null;
File confidential = new File("contracts.txt");
try
{
// create new file
FileWriter fw = new FileWriter(confidential, true);
output = new PrintWriter(fw);
}
catch (FileNotFoundException e) // Problem with file
{
System.out.println("Error: Problem creating the file! Program closing");
System.exit(0);
}
catch (IOException ex)
{
System.out.println("Error: Problem creating the file! Program closing");
System.exit(0);
}
output.print(date);
output.print(" ");
output.print(minutes);
output.print(" ");
output.print(data);
output.print(" ");
output.print(length);
output.print(" ");
output.print(international);
output.print(" ");
output.print(ref);
output.print(" ");
output.print(price);
output.print(" ");
output.print(name);
output.close();
}// end of main`
As you can see, my code is probably wrong and I'm not sure whether or not this method should even be in a seperate class or just stick the code for it in the main class? I appreciate the time it takes to go through my question and I hope someone can help me, as I'm currently about to rip my hair out in frustration of not understanding how to do it.
Add the statement output.print("\n"); at the end so that each record will be in separate line.
output.print(price);
output.print(" ");
output.print(name);
output.print("\n");
I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
I've just started on my college journey ( 'Yay' ). I'm also new to the site so feel free to lecture me on things I may have done wrong as far as asking questions is concerned.
I was given a project, which has already been graded and all, and the program should ==>> first read lines of standard input (Input file name using keyboard) and for each line of input, if the user enters exit, the application terminates; otherwise, the application interprets the line as a name of a text file. The application creates or recreates this file and writes to it two lines of output, the name of the file and the current date and time. The application then closes the file, reopens it for reading, and writes its contents to standard output. The application writes to standard output the name of the file enclosed by square brackets. After writing the file name,
the application writes the contents of the file with each line prefixed by its corresponding line
number, a full colon, and a space.
I have worded it just as my professor did, so I apologize for any unclear statements. Here's what I got for it:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Project1
{
public static void main() throws IOException
{
String input = "";
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
input = sc.nextLine();
try
{
File file = new File (input,".txt"); // Creates pointer to a file.
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
file.createNewFile();
file.getAbsolutePath();
printFileAndDate(file);
}
catch(IOException e)
{
System.out.print("Something wrong :(");
e.printStackTrace();
}
}
System.exit(0);
}
static void printFileAndDate(File temp)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("[ " + temp.getPath() + " ]");
System.out.println(dateFormat.format(cal.getTime()));
}
}
What I attempted to do there was the following:
-Get User Input => Save Input as a file => Call method "printFileAndDate" and print the file along with the current date and time in the correct format.
However, whenever I run it, it always gives me an exception error, which means the file was never really created or that it isn't able to find it.
The list of ISSUEs, I could find :
First, your main method signature is totally wrong
public static void main() throws IOException
change to
public static void main(String[] args) throws IOException
Second, it is not a good practice to throws exception inside main method.
The good practice is to use try catch block
Third, you have your Scanner varialbe after the while loop which does not make sense
while(!sc.equals("exit"))
{
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in); <-?!!!!!!
change to
System.out.println("Enter file here!\n Type 'exit' to terminate");
Scanner sc = new Scanner(System.in);
while(!sc.equals("exit"))
{
Fourth , you define File variable this way
File file = new File (input,".txt"); <-- totally wrong
change to
File file = new File ("input.txt"); <-- if you use relative path
Fifth there is not need for System.exit(0);at the end of main method