why I can't add my answer to readwrite.txt.? - java

I try to add my answer to readwrite.txt, but I don't find my answer every time I run the code.
public static void main(String[] args) {
ArrayList<String> category1=new ArrayList<>();
category1.add("die hard");
category1.add("7.5");
category1.add("mission impossible");
category1.add("8");
category1.add("the expendabels");
category1.add("6");
ArrayList<String> category2=new ArrayList<>();
category2.add("the mask");
category2.add("due date");
ArrayList<String>userchoices=new ArrayList<>();
Scanner s= new Scanner(System.in);
System.out.println("select a movie");
String answer=s.nextLine();
String writepath="files/readwrite.txt";
try {
FileWriter writer=new FileWriter(writepath);
writer.write(answer);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (category1.contains(answer)) {
System.out.println(category1.get(category1.indexOf(answer) + 1) +
(" of 10"));
System.out.println("action");
}
if (answer.equals("action"))
System.out.println(category1);
else if (category2.contains(answer))
System.out.println("comedy");
if (answer.equals("comedy"))
System.out.println(category2);
}
}
I try to add my answer to readwrite.txt, but I don't find my answer every time I run the code.

You need to close your FileWriter when you are done with writing to file. When you call close() writer will flush its internal buffer to disk and you will see that text appears in file. Also it is a must to close any resources when you do not need them.

Related

Access variable in try block

I want to remove the throws FileNotFoundException from the method head and put it into it.
public static String[] read(String file) throws FileNotFoundException {
But then I can't access in (the scanner) anymore! How to handle that?
public static String[] read(String file) {
try {
Scanner in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
// ...
in.close();
// ...
}
Just use try-with-resources so you dont have to worry about closing the scanner object.
try (Scanner in = new Scanner(new FileReader(file))) {
//Your code
}
catch (Exception e) {
}
you can use try with ressource, that permit to close automaticaly your in.
like that
Scanner in ;
try ( in = new Scanner(new FileReader(file))) {
}
catch (Exception e) {
}
The variable in is out of scope outside the try block. You can either do this:
public static String[] read(String file) {
Scanner in = null;
try {
in = new Scanner(new FileReader(file));
}
catch (Exception e) {
}
finally() {
in.close();
}
// ...
}
Or better yet, try with resources
public static String[] read(String file) {
try (Scanner in = new Scanner(new FileReader(file))){
String line = in.nextLine();
// whatever comes next
}
catch (Exception e) {
}
// right here, the scanner object will be already closed
return ...;
}
The in variable is locally scoped to the try block. You can either declared the variable before the try block, or close in within the try block. There's not much use in closing it if it never successfully opened.

Saving input to a file is replaced when re-running

I'm trying to create something similar to a mail server.
Now, I'm supposed to have a file called 'Credentials' that saves the email and password entered each time I run the client.
File Credentials = new File("Server\\Credentials.txt");
try{
if(Credentials.createNewFile()){
System.out.println("Credentials created");
}else {System.out.println("Credentials already exists");}
}catch(Exception error){}
try (
PrintWriter out = new PrintWriter(Credentials, "UTF-8")
) {
out.println("Email: " + email);
out.println("Password: " + password);
} catch(IOException e) {
e.printStackTrace();
}
However, each time a client runs, it replaces the old email and password. Any idea how to make it continue to the next line without replacing? Thank you.
As previously mentioned you have to use the correct constructor, which will append your text instead of overriding.
But I would suggest to do it this way:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
doSomething("test" + i);
}
}
static void doSomething(String text) {
try (PrintWriter test = new PrintWriter(new BufferedWriter(new FileWriter("your path", true)))) {
test.print(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here are some further informations and different approaches for your issue:
How to append text to an existing file in Java?

Output file is only showing last line of the input file

In the output file "CMFTSwitchesnew.txt" only has the last line of the input file. I've tested a few different methods such as changing write.println(input.nextLine()) but I'm not sure now where the issue is.
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
You're creating a PrintWriter in each iteration without using the constructor that allows you to tell the PrintWriter to append data at the end of an already existing file. That way you only see the output of the last time the file was written. Either change that to
PrintWriter write = new PrintWriter(output, true);
or instantiate the PrintWriter outside the while-loop and close it after it.

Deserializing an Object only reads one data

how do read file data from file/Deserializing an object.I have created a file which is binary file which contains list of companies data i am able to add new company and its related data but when i want to read back all the file datas it only gives first company datas and it prints null ..what is the problem below is what i have done
public class CompanyInfo extends Company {
int counter=0;
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("\n");
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("\n");
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("\n");
System.out.println("Enter Closing Rate \n");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
try {
ObjectOutputStream outObjFile =new ObjectOutputStream(new FileOutputStream("companies.dat",true));
Company company = new Company(companyName,companyCode,shareNo,closingRate);
outObjFile.writeObject(company);
outObjFile.writeChars("\n");
outObjFile.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("A file error has occurred. Sorry.");
System.out.println( e.getMessage() );
}
counter++;
}
public void viewcompany(){
try {
ObjectInputStream inObjFile = new ObjectInputStream(
new FileInputStream("companies.dat"));
System.out.println(inObjFile.readObject()); // displays first object
Company company = (Company)inObjFile.readObject(); // restores object
System.out.println(company); // displays restored object
inObjFile.close(); // finished with the file now.
} catch (Exception e) {
System.out.println(e.getMessage());
}
I will do two different ways.
Add all details into hashmap and serialize that object. So while reading back, I can search using "key". Key can be name or ID of company. You can do same with ArrayList as well. Search may be difficult. Immutable collections from Guava are less memory used and more better.
Another solution is create object file with key.dat and put into a directory called company. So easy to read back and do search as well.
finally i found the answer ...Hope it helps to others too..good luck
public class CompanyInfo extends Company {
int counter=0;
private static String filename = "company.dat";
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("Enter Closing Rate");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
File file=new File(filename);
boolean append=true;
ObjectOutputStream out=null;
try {
if (!file.exists()||!append) {
out=new ObjectOutputStream(new FileOutputStream(filename));
}
else
{
out=new AppendableObjectOutputStream(new FileOutputStream (filename, append));
}
Company company = new Company(companyName,companyCode,shareNo,closingRate);
out.writeObject(company);
out.flush();
} catch (Exception e){
e.printStackTrace ();
}finally{
try{
if (out != null) out.close ();
}catch (Exception e){
e.printStackTrace ();
}
}
counter++;
}
public void viewcompany(){
try {
List<Object> results = new ArrayList<Object>();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
try{
while (true) {
results.add(ois.readObject());}
}
catch (OptionalDataException e) {
if (!e.eof) throw e; }
finally {
System.out.println(results);
//System.out.println(((Company)results.get(0)).companyName);
ois.close(); }
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
private static class AppendableObjectOutputStream extends ObjectOutputStream {
public AppendableObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {}
}
}

Not 100% sure on Try /Catch

I have been asked to convert this code with a throw exception IF to a try/catch block. I have set it up but am not sure what to put in lieu of the word output so that it may run. I am not sure after reading the book and oracles info try/catch I see what needs to be done so the txt file will print. I will post code to be modified and then my change with try/catch. thanks for any help.
public class WriteData {
public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
Here is the code changed for the Try/Catch
import java.io.FileNotFoundException;
public class WriteData {
public static void main(String[] args) {
java.io.File file = new java.io.File("scores.txt");
try {
output = new java.io.PrintWriter(file);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
java.io.PrintWriter output = new java.io.PrintWriter(file);
// Write formatted output to the file
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
// Close the file
output.close();
}
}
You are instanciating two times output when it is not needed.
All treatment related to output should be done in the try block so it is not executed if an error happen and the stack is redirected to exception block.
The output should be in a finally block to make sure the file is closed whatever happen.
Doing these correction, your code shoud look like this :
import java.io.*;
public class WriteData {
public static void main(String[] args) {
File file = null;
PrintWriter output = null;
try
{
file = new File("scores.txt");
output = new PrintWriter(file);
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
finally
{
//The output not be instanciated if scores.txt was not found.
if(output != null)
output.close();
}
}
}
In my opinion, this is the best way to handle your case.
try {
output = new java.io.PrintWriter(file); // output is not defined yet
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// Create a file
// This one will throw the FileNotFoundException
java.io.PrintWriter output = new java.io.PrintWriter(file);
You can modify it like this
try {
java.io.PrintWriter output = new java.io.PrintWriter(file);
//rest of the code
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
For your error:
Remove the catch block for IoException from jean-François Savard's solution.
FileNotFoundException is a checked exception thrown by PrintWriter(). As a practice only catch the exceptions declared in API signature.
(In fact keeping any one block should work, as FileNotFoundException extends IOException )

Categories