How to write code data into a text file - java

I just did a simple code which takes user name and phone number and save those into an arraylist by creating object. I want to save those information (name and phonenumber) into a text file so that all old information I can get again. How do I do it? Here is my code ...
import java.util.ArrayList;
import java.util.Scanner;
public class manager {
Scanner input = new Scanner(System.in);
ArrayList <objectclass> Test = new ArrayList <objectclass> ();
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER\n2 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
} else {
System.out.println("Contact not Found!\n");
}
}
}
}
}
}
I want to save all name and number that I store in arraylist into a text file ... how can I do it?
I tried this so far but don't know what to do next ...
import java.io.;
import java.lang.;
import java.util.*;
public class creatfile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("testkyo");
}catch (Exception e){
System.out.println("you have an error");
}
}
public void addRecord(){
x.format();
}
public void closeFile(){
x.close();
}

You need to serialize an object in order to save it onto the file .
here's a tutorial on how to do it, its really simple.
When you serialize an object you can write it onto a file and then load it as it is from there .
EDIT :
example on how you could use this here , i guess the ObjectClass is the thing u want to save so :
class ObjectClass implements Serializable {
String name;
String number;
//constructor , setters , getters and w.e functions .
public static void main (String args[]){
try{
ObjectClass test = new ObjectClass("test",2);
File f = new File("path to file");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(test); // this will write the object as it is onto the file
out.close();
}catch(Exception ex){}
}
}
you wont be able to read the data cuz its serialised , but u can load them as objects like so :
ObjectInputStream in = new ObjectInputStream(new File("path to file"));
ObjectClass test =(ObjectClass) in.readObject(); // u have to cast from Object to Objectclass

what you propably want is an ObjectOutputstream writing your ArrayList to a file via an FileOutputStream when the porgram is exiting and reading the Arraylist with the coresponding InputStreams. See the links below:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

A simple example:
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("./output.txt"));
writer.write("Hello World");
} catch (IOException e) {
System.err.println(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
This will write "Hello World" in the text file named: "output.txt".
Check the java I/O api.
You can find a lot of tutorials on the web about this, like:
Reading, Writing, and Creating Files
Creating, Writing, Reading files using Java Files API of Java 7

Related

I am Lost trying to understand how to take in user input into different excel colums.

The goal of this project is to create a Food Diary.
This diary should contain breakfast, lunch, dinner and Snacks that you consume during the day. The user should be able to enter their food items and save it as a CSV file.
Here is what I have so far
When I write my variables f and t to excel they are in the same cell how can I make it so they are in separate columns
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
FileOutputStream FileName = new FileOutputStream( "MyFooDiary.csv");
System.out.println("Welcome to your food diary");
System.out.println("What is the name of your Food?");
Scanner x = new Scanner(System.in);
String f = x.nextLine();
System.out.println("Was this breakfast, lunch, dinner, or a snack");
Scanner y = new Scanner(System.in);
String t = y.nextLine();
try {
File file = new File(FileName);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write("Date, Food Time, Food Name, Calories, Carbohydrates,
Sugars, Fiber, Protein, Total Fat ");
bw.write(t);
bw.write(f);;
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You need to add a comma , between values to have them in different cells.
Try this method to check if the end of t and the start of f do not have a ",". If neither has a comma then add one to the end of t:
bw.write(t);
//check if the end of t and the start of f do not have a ",". If neither has a comma then add one to the end of t
if (t.endsWith(",") == false && f.startsWith(",") == false)
{
t = t + ",";
}
bw.write(f);
I would suggest writing a special method to do a check like this on two variables so that you can call it from anywhere, also I note that you are missing a "," at the end of this line Sugars, Fiber, Protein, Total Fat ");. is should have Fat, "); (notice the comma).

How can I compare an integer and a file name?

I am trying to make a login/password program which asks if you have an account and you can also make one.
By account I mean the program will give you a random 8 digit number.
I also have a FileWriter which creates a file based on the ID you were given. And I have a FileReader which will eventually read what you previously exported to your file so you can update it.
The problem I have is that when I ask the user if they have an account already, if they say yes it will ask the user for their UserID.
My plan was that when it read your UserID it would scan the folder I have my .java file saved in and look for a .txt file with the same name as your UserID. For example, if you make an account and the UserID it gives you is 12345678 it will create a file named 12345678 and then when you input you UserID it will scan to see if that file exists.
Currently The problem that occurs is the it prints
Error File Not Found(the catch String I wrote)
even though I have that file in the folder.
I think there is something wrong with how I am comparing to see if the UserID matches any file name.
The "Login" class.
import java.awt.*;
import hsa.Console;
import java.util.Random;
import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class Login
{
static Console c;
static Login player1;
public static void main (String[] args)
{
player1 = new Login ();
player1.FileReaderTest (25756326);
//player1.Userlogin (); //I think it has something to do with this
} // main method
public void Userlogin (File input)
{
c = new Console ();
Random rand = new Random ();
c.println ("Hello do you have an account?");
String Q1 = c.readLine ();
Q1 = Q1.toUpperCase ();
if (Q1.equals ("YES"))
{
c.println ("Please input your User ID");
int login = c.readInt ();
if (String.valueOf(login).equals (input))//I think it has something to do with this
{
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
}
else if (Q1.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (99999999);
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
}
while (!Q1.equals ("YES") && !Q1.equals ("NO")) //While Q1 != YES || NO
{
c.println ("Please Answer the question with Yes or No");
c.println ("Hello do you have an account?");
String Q2 = c.readLine ();
Q2 = Q2.toUpperCase ();
if (Q2.equals ("YES"))
{
c.println ("Ok lets start");
break;
}
else if (Q2.equals ("NO"))
{
c.println ("Please enter your name ");
String name = c.readLine ();
int UserID = rand.nextInt (89999999) + 10000000;
c.println ("Your User ID is " + UserID);
player1.FileCreation (UserID);
player1.FileReaderTest (UserID);
break;
}
} //While Q1 != YES || NO
} //Public void Main
public void FileReaderTest (int UserID)
{
File input = new File (String.valueOf (UserID));
player1.Userlogin (input);
try
{
FileReader reader = new FileReader (input);
BufferedReader buf = new BufferedReader (reader);
String line1 = buf.readLine ();
String line2 = buf.readLine ();
buf.close ();
c.println (line1);
c.println (line2);
}
catch (FileNotFoundException e)
{
c.println ("Error File Not Found");
}
catch (Exception e)
{
c.println ("ERROR");
}
}
public void FileCreation (int UserID)
{
try
{
Writer writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (String.valueOf (UserID)), "utf-8"));
}
catch (IOException ex)
{
}
}
} // Login class
So, you have a File input, and you want to compare the name of the file, so you instead want
String.valueOf(login).equals (input.getName());
If you are getting an error on
File input = new File (String.valueOf (UserID));
then note: "2.txt", for example, is very different than a file named just "2" (which is worth mentioning because Windows hides file extensions by default)
And if you aren't giving the full path to the file, then that file has to be in your "classpath", which if you don't understand, better to give the full path to the file.
FileNotFound is not thrown after a comparison but by your FileReader when it is created. FileReader tells you that there is not file named as such. Since you said that you did create the file, there can be a few explanations:
Maybe the file you created is in the wrong folder. The default folder for a java program is the project folder. Make sure that you have your file in the right folder. Else you can give the full path as an argument for the FileReader: "/my/full/path/filename.extension".
It can also be a problem of extension. If you are using a Windows OS, the extension may be hidden in the file explorer. Right clic on your file and check whether there is such an extension (ex: ".txt")
Eventually you can open the file with a FileWriter under Java, and try to create the file within your program. You will see more easily which file Java is trying to access and it will help you identify your issue.
Since you have mentioned that you need to create the text file associated with the UserId, I would suggest adding the ".txt" in the FileReaderTest class. Something similar to this :
File input = new File (String.valueOf (UserID)+".txt");
Or more conveniently
File input = new File (Integer.toString(UserID)+".txt");
I think this solves your query.

Problems writing to and reading from a file

I am new to programming (Sorry if I ask an easy question) and I have a problem with my program dealing with writing to and reading from a file. To start off I ask the user what they want their username and password to be. Then to simply check if what I was doing was correct, I tried to read the file and then print out the same information. Here is my code:
public void createAccount()
{
try
{
FileWriter doc = new FileWriter("Username.ctxt", true);
System.out.print("Enter your desired Username: ");
myUsername = keyboard.next();
System.out.println();
System.out.print("Enter your desired Password: ");
myPassword = keyboard.next();
System.out.println();
String doc2 = myUsername + " " + myPassword + "\n";
doc.write(doc2, 0, doc2.length());
doc.close();
}
catch(IOException e)
{
System.out.println("Error: " + e.getMessage());
}
retrieveAccount();
}
public void retrieveAccount()
{
try
{
BufferedReader reader = new BufferedReader(new FileReader("Username.ctxt"));//
String user = new String("");//username
String pass = new String("");//password
int stop;
String line = null;
System.out.print("Enter your username: ");//allows computer to search through file and find username
username = keyboard.next();
while ((line = reader.readLine()) != null)
{
scan = reader.readLine();
stop = scan.indexOf(" ");
user = scan.substring(0, stop);
System.out.println(user);
pass = scan.substring(stop + 1);
System.out.println(pass);
if(user.equals(myUsername))
{
System.out.println("Your password is: " + pass);
break;
}
}
}
catch(IOException a)
{
System.out.println("Error: " + a.getMessage());
}
}
So what I want to happen is:
Enter desired username: jake101
Enter desired password: coolKid
Enter your username: jake101
your password is: coolKid
But what actually happens is, is and out of bounds exception(-1)
This is happening because when I use indexOf(" "); it searches for a space. And when it returns negative 1 it means there is no space. What i believe is happening is that i am not writing to the same document i am trying to read from. If anybody can help me figure out what i am doing wrong this would help!
You're double readling the contents of the file...
You first read a line from the file using...
while ((line = reader.readLine()) != null) {
The, straight after that, you read another line using...
String scan = reader.readLine();
Get rid of the second line read...
The issue is that you are calling readline twice in same loop
while ((line = reader.readLine()) != null)
{
scan = reader.readLine();
Change the above to following and it will work
while ((line = reader.readLine()) != null)
{
String scan = line;
The problem seems to be in your retrieveAccount() method, try closing ur reader object. U have opened the file in retrieveAccount() and never closed (so its stil under locked state for other applns/mthds/threads to access).
Try adding reader.close() before end of try block
I would suggest you to create seperate methods for createAccount,retrieveAccount,writeToFile and readToFile. A method should always be responsible to handle single modules. Is the actual responsibillity of createAccount method to read from a file? I would totally say no. Firstly, because low coupling - high cohesion principles are not followed and secondly, because reusabillity does not exist in this way. There are other issues that occur with your currect approach but since you are still in the beginning is expected.
I will provide you with some parts of the things you could do, however, there will be some parts that you should work on your own, like creating the User Class ( it shouldn't be difficult and it will help you learn)
So let's see.
public void createAccount(User user, ListInterface<User> userList)
throws AuthenticationException {
if (!userList.exists(user)) {
userList.append(user);
} else {
throw new AuthenticationException(
"You cannot add this user. User already exists!");
}
}
public boolean authenticate(User user, ListInterface<User> userList)
throws AuthenticationException {
for (int i = 1; i <= userList.size(); i++) {
if (user.equals(userList.get(i))
&& user.getPassword().equals(
userList.get(i).getPassword())) {
return true;
}
}
return false;
}
public void readFromFile(String fileName, ListInterface<User> userList) {
String oneLine, oneLine2;
User user;
try {
/*
* Create a FileWriter object that handles the low-level details of
* reading
*/
FileReader theFile = new FileReader(fileName);
/*
* Create a BufferedReader object to wrap around the FileWriter
* object
*/
/* This allows the use of high-level methods like readline */
BufferedReader fileIn = new BufferedReader(theFile);
/* Read the first line of the file */
oneLine = fileIn.readLine();
/*
* Read the rest of the lines of the file and output them on the
* screen
*/
while (oneLine != null) /* A null string indicates the end of file */
{
oneLine2 = fileIn.readLine();
user = new User(oneLine, oneLine2);
oneLine = fileIn.readLine();
userList.append(user);
}
/* Close the file so that it is no longer accessible to the program */
fileIn.close();
}
/*
* Handle the exception thrown by the FileReader constructor if file is
* not found
*/
catch (FileNotFoundException e) {
System.out.println("Unable to locate the file: " + fileName);
}
/* Handle the exception thrown by the FileReader methods */
catch (IOException e) {
System.out.println("There was a problem reading the file: "
+ fileName);
}
} /* End of method readFromFile */
public void writeToFile(String fileName, ListInterface<User> userList) {
try {
/*
* Create a FileWriter object that handles the low-level details of
* writing
*/
FileWriter theFile = new FileWriter(fileName);
/* Create a PrintWriter object to wrap around the FileWriter object */
/* This allows the use of high-level methods like println */
PrintWriter fileOut = new PrintWriter(theFile);
/* Print some lines to the file using the println method */
for (int i = 1; i <= userList.size(); i++) {
fileOut.println(userList.get(i).getUsername());
fileOut.println(userList.get(i).getPassword());
}
/* Close the file so that it is no longer accessible to the program */
fileOut.close();
}
/* Handle the exception thrown by the FileWriter methods */
catch (IOException e) {
System.out.println("Problem writing to the file");
}
} /* End of method writeToFile */
Useful Information:
The userList is a dynamic linked list that uses generics (ListInterface<User>)
if you dont want to use generics you could just say ListInterface userList, whereever it appears.
Your User class should implement the comparable and include the methods stated below:
public int compareTo(User user) {
}
public boolean equals(Object user) {
}
Always try to create "plug-an-play" methods(not hardcoded), that's the reason I pass as a parameter the userList.
Note that, in case that you dont use generics, typecast might be needed. Otherwise, you will get compilation errors.
If you have any questions let me know.

input values to console from a text file instead of manually entering the value

I have a program Main.java:
public class Main {
public static void main() throws FileNotFoundException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no: \t");
int sq=0;
try {
sq=Integer.parseInt(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sq*sq);
}
}
I am not supposed to edit the above code(Main.java) and I should execute this program from another java program. So, I figured out the following code:
public class CAR {
public static void main(String[] args) {
try {
Class class1 = Class.forName("executor.Main"); // executor is the directory in which the files Main.java and CAR.java are placed
Object object = class1.newInstance();
Method method = class1.getMethod("main", null);
method.invoke(object, null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
By running CAR.java, the following is the output:
Enter no:
2 // this is the number I entered through the console
square is: 4
This works fine.But now, I need to input value to "sq" (variable in Main.java) not from the console but from a text file using the program CAR.java without editing Main.java. And I couldn't figure out how to do this with out editing the Main.java.
For example, If chech.txt has content as: 10 100.
Then, by running CAR.java I should read the value 10 and give it to the waiting console to be asigned to the values of "sq" and compare the output printed on the console with 100.
And print the output of the CAR.java as "Test passed".
Please suggest a solution for this.
The following code snippet could be added to CAR.java to read values from a file:
File f = new File("check.txt");
BufferedReader bf = new BufferedReader(new FileReader(f));
String r = bf.readLine();
String[] r1 = r.split(" ");
System.out.println("Input= " + r1[0] + " Output= " + r1[1]);
System.setIn() did the magic...
It specifies the jvm, to change the way of taking inputs from "System.in". Example:
System.setIn(new FileInputStream("chech.txt"));
This takes the input from "check.txt" instead of waiting for input from the console. Example program:
public class systemSetInExample {
public static void main(String[] args) {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter input: ");
String st=br.readLine(); // takes input from console
System.out.println("Entered: "+st);
System.setIn(new FileInputStream("test.txt"));
br=new BufferedReader(new InputStreamReader(System.in));
st=br.readLine(); // takes input from file- "test.txt"
System.out.println("Read from file: "+st);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Dead Simple but lengthy Java PrintWriter problem

The problem is it finds the key word "dodge" creates the file but doesn't write to it. I had this problem earlier and I flushing then closing the file fixed it, but that did not work this time.
Also WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]); towards the bottom errors out and says ArrayIndexOutOfBoundsException: -2 I'm not sure why because "using" should never be found at position -1.
import java.io.*;
import javax.swing.JOptionPane;
public class InputLog {
private BufferedReader CombatLog;
private PrintWriter CharacterFile;
private String[] CurrentLine;
InputLog(){
try{
CombatLog = new BufferedReader(new FileReader("127401175162_chatlog.txt"));
do{
try{
CurrentLine = CombatLog.readLine().split(" ");
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry cannot open UserSettings File");
}
DetermineType();
}while(CombatLog.ready());
CharacterFile.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Could not open next line of combatlog " + e);
}
}
public void WriteToFile(String S){
try{
CharacterFile = new PrintWriter(new File(CurrentLine[3]));
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry can't write " + CurrentLine[3] +" To file");
}
CharacterFile.flush();
CharacterFile.print(S+ " ");
}
public void WriteToFileLn(String S){
try{
CharacterFile = new PrintWriter(new File(CurrentLine[3]));
}
catch(IOException e){
JOptionPane.showMessageDialog(null, "Sorry can't write " + CurrentLine[3] +" To file");
}
CharacterFile.flush();
CharacterFile.println(S+ " ");
}
public int ReturnWordsIndex(String S){
for(int i=0;i<CurrentLine.length;i++){
if(CurrentLine[i].equals(S))
return i;
}
return -1;
}
private void DetermineType(){
for(String A: CurrentLine)
if(A.equals("attacks")){
JOptionPane.showMessageDialog(null, "found dodge");
WriteToFile(CurrentLine[2]);
WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]);
WriteToFile("(dodge).");
WriteToFileLn(CurrentLine[ReturnWordsIndex("attacks")-1]);
}
}
public static void main(String args[]){
new InputLog();
}
}
Thanks, Macaire
Edit: I found out that i am simply writing one string, creating a new file, then writing another character. How can i not delete the file, and just rewrite to it?
How can i not delete the file, and just rewrite to it?
I assume that you mean append to it. (What you are currently doing is rewriting it.)
If so, just use FileWriter(file, true) to create a Writer that will start writing at the current end of the file; e.g.
CharacterFile = new PrintWriter(new FileWriter(new File(CurrentLine[3])));
Note: it is bad style for a Java variable or method name to start with an upper-case letter.
WriteToFile(CurrentLine[ReturnWordsIndex("using")-1]); causes an ArrayIndexOutOfBoundsException: -2 because the word "using" is not found (so ReturnWordsIndex("using") returns -1).
You need an if/then statement so that you don't try to index CurrentLine if the word wasn't found.
In response to your edit, open the file outside of the WriteToFile and WriteToFileLn functions.

Categories