Java read file with scanner - java

I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}

after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}

Related

Increment number every time program runs

I want to increment the count every time my program runs. I tried running below code but it keeps on printing 1 every time i run the program. Also anything special i need to do to increase the date.
public class CounterTest {
int count = 0;
public static void main(String[] args) {
CounterTest test1 = new CounterTest();
test1.doMethod();
}
public void doMethod() {
count++;
System.out.println(count);
}
}
You could simply create a properties file for your application to keep track of such things and application configuration details. This of course would be a simple text file containing property names (keys) and their respective values.
Two small methods can get you going:
The setProperty() Method:
With is method you can create a properties file and apply whatever property names and values you like. If the file doesn't already exist then it is automatically created at the file path specified:
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
outputStream.close();
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
If you don't already contain a specific properties file then it would be a good idea to call the above method as soon as the application starts (perhaps after initialization) so that you have default values to play with if desired, for example:
if (!new File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
The above code checks to see if the properties file named config.properties already exists (you should always use the .properties file name extension). If it doesn't then it is created and the property name (Key) is applied to it along with the supplied value for that property. Above we are creating the ApplicationRunCount property which is basically for your specific needs. When you look into the config.properties file created you will see:
#Mon Sep 28 19:07:08 PDT 2020
ApplicationRunCount=0
The getProperty() Method:
This method can retrieve a value from a specific property name (key). Whenever you need the value from a particular property contained within your properties file then this method can be used:
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
Your Task:
What is confusing here is you say you want to keep track of the number of times your Program is run yet you increment your counter variable named count within a method named doMethod(). This would work if you can guarantee that this method will only run once during the entire time your application runs. If this will indeed be the case then you're okay. If it isn't then you would possibly get a count total that doesn't truly represent the actual number of times your application was started.
In any case, with the scheme you're currently using, you could do this:
public class CounterTest {
// Class Constructor
public CounterTest() {
/* If the config.properties file does not exist
then create it and apply the ApplicationRunCount
property with the value of 0. */
if (!new java.io.File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
}
public static void main(String[] args) {
new CounterTest().doMethod(args);
}
private void doMethod(String[] args) {
int count = Integer.valueOf(getProperty("config.properties",
"ApplicationRunCount"));
count++;
setProperty("config.properties", "ApplicationRunCount",
String.valueOf(count));
System.out.println(count);
}
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new
java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
}
Whenever you start your application you will see the run count within the Console Window. Other useful methods might be removeProperty() and renameProperty(). Here they are:
/**
* Removes (deletes) the supplied property name from the supplied property
* file.<br>
*
* #param propertiesFilePath (String) The full path and file name of the
* properties file you want to remove a property name from.<br>
*
* #param propertyName (String) The property name you want to remove from
* the properties file.<br>
*
* #return (Boolean) Returns true if successful and false if not.
*/
public static boolean removeProperty(String propertiesFilePath,
String propertyName) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(propertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
return true;
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return false;
}
/**
* Renames the supplied property name within the supplied property file.<br>
*
* #param propertiesFilePath (String) The full path and file name of the
* properties file you want to rename a property in.<br>
*
* #param oldPropertyName (String) The current name of the property you want
* to rename.<br>
*
* #param newPropertyName (String) The new property name you want to use.<br>
*
* #return (Boolean) Returns true if successful and false if not.
*/
public static boolean renameProperty(String propertiesFilePath, String oldPropertyName,
String newPropertyName) {
String propertyValue = getProperty(propertiesFilePath, oldPropertyName);
if (propertyValue == null) { return false; }
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(oldPropertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false ;}
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
return setProperty(propertiesFilePath, newPropertyName, propertyValue);
}
Try this.
public class CounterTest {
static final Path path = Path.of("counter.txt");
int count;
CounterTest() throws IOException {
try {
count = Integer.valueOf(Files.readString(path));
} catch (NoSuchFileException | NumberFormatException e) {
count = 0;
}
}
public void doMethod() throws IOException {
++count;
System.out.println(count);
Files.writeString(path, "" + count);
}
public static void main(String[] args) throws IOException {
CounterTest c = new CounterTest();
c.doMethod();
}
}
You can't the only way is to use a Database or simpler use a txt file to save the number and every time you run your app reads the txt file and gets the number.
Here is How to do it:
This is the Main class:
package main;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String path = "C:\\Example.txt";
int number = 0;
try {
ReadFile file = new ReadFile(path);
String[] aryLines = file.OpenFile();
try {
number = Integer.parseInt(aryLines[0]);
} catch (Exception e) {
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(number);
number++;
File txtfile = new File(path);
if (txtfile.exists()) {
txtfile.delete();
try {
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
} else {
try {
System.out.println("no yei");
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
}
}
}
the class that writes anything you need:
package main;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
public String path;
public boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textline) throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textline);
print_line.close();
}
}
And this one is the one that gets the text on the file:
package main;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}

How to prevent the block from being displayed, finally, if there is no path to the file

Problem: if the path to the file was not specified in the arguments, then it still displays the phrase "The file was closed". This works 2 times. In uploadToFile and read method. I pass one path in the arguments, and the second is written in the DownloadFile
public class Task implements AutoCloseable {
public static void main(String[] args) throws IOException {
String DownloadFile = "C:\\Users\\VGilenko\\IdeaProjects\\Task\\src\\main\\resources\\Out.txt";
Map<String, Departament> departments = new HashMap<>();
String path = args.length > 0 ? args[0] : null;
read(path, departments);
transferToDepartment(departments, DownloadFile);
}
private static void uploadToFile(List download, String path) {
int i = 0;
try (FileWriter writer = new FileWriter(path, false)) {
...
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
} finally {
System.out.println("The file was closed");
}
}
public static void transferToDepartment(Map<String, Departament> departments, String downloadFile) {
List<String> download = new ArrayList<>();
...
}
uploadToFile(download, downloadFile);
}
public static void read(String path, Map<String, Departament> departments) throws IOException {
assert path != null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "CP1251")); br) {
.....
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found, check the path");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Correct the file path, step out of the array");
} catch (NullPointerException e) {
System.out.println("You forgot to register the path to the file");
} finally {
System.out.println("The file was closed");
}
}
#Override
public void close() {
System.out.println("The file was closed");
}
}
You have your printout "The file was closed" in your finally statement. If you don't specify a file, you will catch an Exception, and your finally block will be executed.
An easy fix would be to check for the existence of the path (not being empty, not being null).

Operations on file with multithreading

I'm trying to work with multiThreading and I want to write a code that must do some operations on a specific file called data.txt.
There must be three writers and three readers,writer 1 has to write a random char from A to Z,writer 2 has to write a random number from 1 to 100,writer 3 has to write a random char from this set of characters {*%$##!&}.
Then readers must read a character from the file data.txt and then reader 1 write this character in file 1.txt,reader 2 write this character in file 2.txt and reader 3 write this character in file 3.txt.
If there was no character in data file to read the readers must wait until the writers add something to the data file.
I have wrote two classes called WriterInFile and ReaderFromFile that extends Thread class but it seems that the ReaderFromFile doesn't work correctly(It doesn't read any characters from data file and doesn't add anything to files 1.txt,2.txt,3.txt)
This is the code for ReaderFromFile class:
import java.io.*;
public class ReaderFromFile extends Thread {
private static FileReader reader;
private int numberOfReader;
ReaderFromFile(int numberOfReader, FileReader reader) {
this.numberOfReader = numberOfReader;
ReaderFromFile.reader = reader;
}
public void run() {
for (int i = 0; i < 5; i++) {
String s = null;
try {
s = readFrom();
} catch (IOException e) {
e.printStackTrace();
}
FileWriter writer;
switch (numberOfReader) {
case 1:
try {
writer = new FileWriter("1.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 2:
try {
writer = new FileWriter("2.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 3:
try {
writer = new FileWriter("3.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/**
* #return the character that has been reed
*/
private synchronized String readFrom() throws IOException {
String s = null;
while (!reader.ready()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
s = String.valueOf(reader.read());
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
return s;
}
}
this is the WriterInFile class:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class WriterInFile extends Thread {
private static FileWriter writer;
private int numberOfReader;
WriterInFile(int numberOfReader, FileWriter writer) {
this.numberOfReader = numberOfReader;
WriterInFile.writer = writer;
}
public void run() {
for (int i=0;i<5;i++){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (numberOfReader) {
case 1:
writeChar();
break;
case 2:
writeNumber();
break;
case 3:
writeShape();
break;
}
}
}
private synchronized void writeChar() {
String s = getRandomChar();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeNumber() {
String s = getRandomNumber();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeShape() {
String s = getRandomShape();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private String getRandomChar() {
double randomDouble = Math.random();
randomDouble = randomDouble * 26;
int randomInt = (int) randomDouble;
return String.valueOf((char)(randomInt+'A'));
}
private String getRandomNumber() {
double randomDouble = Math.random();
randomDouble = randomDouble * 100 + 1;
int randomInt = (int) randomDouble;
return String.valueOf(randomInt);
}
private String getRandomShape() {
String chars = "*%$##!&";
Random rnd = new Random();
char randomChar = chars.charAt(rnd.nextInt(chars.length()));
return String.valueOf(randomChar);
}
}
and this is the main file:
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("data.txt");
FileReader reader = new FileReader("data.txt");
//creating writers
WriterInFile writer1 = new WriterInFile(1, writer);
WriterInFile writer2 = new WriterInFile(2, writer);
WriterInFile writer3 = new WriterInFile(3, writer);
// creating readers
ReaderFromFile reader1 = new ReaderFromFile(1, reader);
ReaderFromFile reader2 = new ReaderFromFile(2, reader);
ReaderFromFile reader3 = new ReaderFromFile(3, reader);
writer1.start();
writer2.start();
writer3.start();
reader1.start();
reader2.start();
reader3.start();
Thread.sleep(10000);
writer.close();
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

Reading Multiple Files Java

I'm new here, and I got a problem when I'm trying to read a file.
Here is my code
public void openFile()
{
try
{
if(Board.state == Board.STATE.LEVEL1)
{
scan = new Scanner(new File("D://OOP Photos//Map.txt"));
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
try
{
if(Board.state == Board.STATE.LEVEL2)
{
scan = new Scanner(new File("D://OOP Photos//Map1.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
try
{
if(Board.state == Board.STATE.LEVEL3)
{
scan = new Scanner(new File("D://OOP Photos//Map2.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
}
If I comment out the if statement it is okay, but if I leave it there, it will throw a NullPointerException in the next method:
public void readFile()
{
while(scan.hasNext())
{
for(int i = 0; i < 10; i++)
{
if(scan.hasNext())
{
Map[i] = scan.next();
}
}
}
}
Can you help me ?
Thank You :)
Do something like this:
public static void main(String args[]) {
String filename;
if(Board.state == Board.STATE.LEVEL1) {
filename = "D://OOP Photos//Map1.txt";
}
else if (Board.state == Board.STATE.LEVEL2) {
filename = "D://OOP Photos//Map2.txt";
}
else if (Board.state == Board.STATE.LEVEL3) {
filename = "D://OOP Photos//Map3.txt";
}
readFile(filename);
}
public void readFile(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
int i = 0;
while(scan.hasNext()) {
Map[i] = scan.next();
i++;
}
}
catch(FileNotFoundException e) {
System.out.println("Error loading MAP !!! ");
}
}
Before each IF statement simply print out the values of Board.state and Board.STATE.LEVELx? That will tell you exactly why your IFs are all false. Or just set a breakpoint and inspect the values.
Also try changing your == in the IFs to .equals().
Your app logic makes me confused. Why not jsut make simple public Scanner openFile(String filePath) method, with one try / catch block, with one Scanner scan = new Scanner(new File(filePath))?
Here's something to consider:
public static class Board {
// I'm assuming this is what's happening?
public static State state = State.LEVEL1;
public enum State {
LEVEL1("Map.txt"), LEVEL2("Map1.txt"), LEVEL3("Map2.txt");
private final String fileName;
private State(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
}
};
public void openFile() {
if (Board.state == null)
throw new RuntimeException("board state not set");
File file = new File("D:/OOP Photos/", Board.state.getFileName());
try (Scanner scan = new Scanner(file)) {
// do the scanning
} catch (FileNotFoundException fnfe) {
// handle file not found
} catch (Exception e) {
// handle other errors
}
}

ObjectOutputStream, ObjectInputStream, and headers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to understand object serialization better, so I am practicing with some code I got from my textbook. (My textbook doesn't explain how to read and write/append objects to a serialization file every time the program starts, which is what I need to do.) I took their program, which just overwrites existing data in a file with the objects from the current session, and add code to it so that it will append the objects and read the whole file instead. I found something really useful here: Appending to an ObjectOutputStream but even if I create a subclass of ObjectOutputStream, override the writeStreamHeader method, and call this subclass if the file already exists, which is what they did, it still throws a CorruptedStreamException. My guess is that I would need to set the pointer back to the beginning of the file, but that doesn't seem to be necessary as there is only one ObjectOutputStream. So, my question is, what else could I possibly need to do?
EDIT: Here is some code.
WriteData.java
import java.io.*;
import java.util.Scanner;
public class WriteData
{
private int number;
private String name;
private float money;
private ObjectInputStream testopen;
private ObjectOutputStream output; //This is for the output. Make sure that
//this object gets an instance of FileOutputStream so that it can write objects
//to a FILE.
private AppendObjectOutputStream appendobjects;
static Scanner input = new Scanner(System.in);
static DataClass d;
public void openfile()
{
//Try opening a file (it must have the ".ser" extension).
try
{
//output = new ObjectOutputStream(new FileOutputStream("test.ser"));
testopen = new ObjectInputStream(new FileInputStream("test.ser"));
}
//If there is a failure, throw the necessary error.
catch (IOException exception)
{
try
{
output = new ObjectOutputStream(new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end case createfile
if (testopen != null)
{
try
{
testopen.close();
appendobjects = new AppendObjectOutputStream(
new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writedata()
{
//write the data until the user enters a sentry value.
System.out.println("Enter CTRL + z to stop input.\n");
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
while (input.hasNext())
{
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
try
{
number = input.nextInt();
name = input.next();
money = input.nextFloat();
//Make object with that data
d = new DataClass(number, name, money);
//write it to the file
if (output != null)
{
output.writeObject(d);
}
else if (appendobjects != null)
{
appendobjects.writeObject(d);
}
}
catch (IOException e)
{
System.out.println("Error writing to file.");
return;
}
}
System.out.println("\n");
} //end writedata
public void closefile()
{
try
{
if (output != null)
{
output.close();
}
else if (appendobjects != null)
{
appendobjects.close();
}
}
catch (IOException e)
{
System.out.println("Error closing file. Take precautions");
System.exit(1);
}
}
}
DataClass.java
import java.io.Serializable;
public class DataClass implements Serializable
{
private int someint;
private String somestring;
private float somefloat;
public DataClass(int number, String name, float amount)
{
setint(number);
setstring(name);
setfloat(amount);
}
public void setint(int i)
{
this.someint = i;
}
public int getint()
{
return someint;
}
public void setstring(String s)
{
this.somestring = s;
}
public String getstring()
{
return somestring;
}
public void setfloat(float d)
{
this.somefloat = d;
}
public float getfloat()
{
return somefloat;
}
}
AppendObjectOutputStream.java
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
public class AppendObjectOutputStream extends ObjectOutputStream
{
public AppendObjectOutputStream(FileOutputStream arg0) throws IOException
{
super(arg0);
// TODO Auto-generated constructor stub
}
//This is a function that is default in ObjectOutputStream. It just writes the
//header to the file, by default. Here, we are just going to reset the
//ObjectOutputStream
#Override
public void writeStreamHeader() throws IOException
{
reset();
}
}
ReadData.java
import java.io.*;
import java.util.Scanner;
public class ReadData
{
private FileInputStream f;
private ObjectInputStream input; //We should the constructor for this
//object an object of FileInputStream
private Scanner lines;
public void openfile()
{
try
{
f = new FileInputStream("test.ser");
input = new ObjectInputStream (f);
//input.reset();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void readdata()
{
DataClass d;
System.out.printf("%-15s%-12s%10s\n", "Account Number", "First Name",
"Balance");
try
{
while (true)
{
d = (DataClass)input.readObject(); //define d
//read data in from d
System.out.printf("%-15d%-12s%10.2f\n", d.getint(), d.getstring(),
d.getfloat());
}
}
catch (EOFException eof)
{
return;
}
catch (ClassNotFoundException e)
{
System.err.println("Unable to create object");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void closefile()
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException ex)
{
System.err.println("Error closing file.");
System.exit(1);
}
}
}
SerializationTest.java
public class SerializationTest
{
public static void main(String[] args)
{
ReadData r = new ReadData();
WriteData w = new WriteData();
w.openfile();
w.writedata();
w.closefile();
r.openfile();
r.readdata();
r.closefile();
}
}
I suggest to do it this way
ObjectOutputStream o1 = new ObjectOutputStream(new FileOutputStream("1"));
... write objects
o1.close();
ObjectOutputStream o2 = new AppendingObjectOutputStream(new FileOutputStream("1", true));
... append objects
o2.close();
it definitely works.
import EJP;
import Evgeniy_Dorofeev;
public class answer
{
private String answera, answerb;
public answer(String a, String b)
{
answera = a;
answerb = b;
}
public void main(String[] args)
{
answer(EJP.response(), Evgeniy_Dorofeev.response());
System.out.println(answera + '\n' + answerb);
}
}
You need to add a 'true' for the append parameter of new FileOutputStream() in the case where you are appending. Otherwise you aren't. Appending, that is.

Categories

Resources