Appending an array to a binary file - java

Hi there I have been having trouble appending entered data to the end of a binary file, having looked up how to do so I found a solution here on stack overflow:
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
In this piece of code allTowns is my array in which the data I wish to add is held. The problem I am getting is that when I run my program and it displays what is in the file at the end this piece of code never writes to the file at all, I was wondering if anyone could help me understand why this does not work or even just recommend a different method if necessary.
My full code (this part is currently commented out so one can easily create the file):
import java.util.*;
import java.io.*;
public class CoastaslTowns implements Serializable
{
public static Scanner input = new Scanner(System.in);
String name, county;
int population, area;
public static int count = 0;
public static int continuation = 0;
public static CoastaslTowns[] allTowns = new CoastaslTowns[50];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int loop1 = 0;
for (int i=0; i < 50; i++) {
allTowns[i] = new CoastaslTowns();
}
while (loop1 == 0) {
System.out.println("Please enter the name of the town.");
String nameEntered = input.nextLine();
System.out.println("Please enter the county in which the town resides.");
String countyEntered = input.nextLine();
System.out.println("Please enter the population of the town.");
int populationEntered = input.nextInt();
System.out.println("Please enter the area of the town.");
int areaEntered = input.nextInt();
input.nextLine();
System.out.println("Are you satisfied with your entries?");
String satisfaction = input.nextLine();
if (satisfaction.equals("yes")) {
loop1 = 5;
System.out.println("Thank you for entering your details");
continuation = 1;
}
else if (satisfaction.equals("no")) {
System.out.println("Would you like to continue and enter more towns?");
String countychecker = input.nextLine();
if (countychecker.equals("yes")) {
}
else {
break;
}
}
writeToFile(nameEntered, countyEntered, populationEntered, areaEntered);
}
ReturnTowns();
}
public static void inputVariations(){
}
public static void writeToFile(String nameEntered, String countyEntered, int populationEntered, int areaEntered) {
int loop2 = 0;
while (loop2 == 0){
allTowns[count].population = populationEntered;
allTowns[count].name = nameEntered;
allTowns[count].county = countyEntered;
allTowns[count].area = areaEntered;
if (continuation == 1) {
loop2 = 1;
}
else {
loop2 = 1;
}
count = count + 1;
}
try {
FileOutputStream fileOut = new FileOutputStream("BinaryWrite.hgal");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(allTowns);
out.close();
fileOut.close();
} catch (IOException i) {}
/*
try {
ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("BinaryWrite.hagl", true));
out.writeObject(allTowns);
out.flush ();
}
catch (Exception e){
System.out.println("IMPOSSSIBLE");
}
*/
}
public static void ReturnTowns(){
{
int x = 0;
CoastaslTowns[] bw = null;
try {
FileInputStream fileIn =
new FileInputStream("BinaryWrite.hgal");
ObjectInputStream in = new ObjectInputStream(fileIn);
bw = (CoastaslTowns[]) in.readObject();
while (bw[x].population != 0) {
System.out.println(bw[x].name);
System.out.println(bw[x].county);
System.out.println(bw[x].population);
System.out.println(bw[x].area);
System.out.println();
x++;
}
in.close();
fileIn.close();
} catch (IOException i) {
} catch (ClassNotFoundException c) {
}
}
}
}
Any help would be greatly appreciated.

Related

Java error: method readFile() in class cannot be applied to given types

im a first year computer science student learning java and im trying to read a csv file line by line and convert each row to an object, then create an array out of these objects with each element separated by a comma ",". Program keeps returning unusual error: method readFile() in class cannot be applied to given types. im not sure what to do.
main class:
import java.io.*;
import java.util.*;
public class FlightOperations
{
static String fileName = "LaxData.csv";
public static void main(String[] args)
{
// Parsing a CSV file into Scanner class constructor
Scanner sc = new Scanner(System.in);
int fileLength = 0;
fileLength = getFileCount(fileName);
int again = 0;
Date[] LAXarray = new Date[fileLength];
LAXarray = readFile(fileName, fileLength);
menu(LAXarray, sc);
do
{
try
{
System.out.println("\n\nRun program? (1)YES (2)NO");
again = sc.nextInt();
if(again == 1)
{
menu(LAXarray, sc);
}
else
{
System.exit(1);
}
}
catch (InputMismatchException exception)
{
System.out.println("\nInvalid input");
sc.next();
}
}
while (again != 1 || again != 2);
sc.close(); // closes the scanner
}
readFile class:
public static Date[] readFile(String fileName)
{
FileInputStream fileStream = null;
InputStreamReader Read;
BuffferedReader bufRead;
/* int fileLength = getFileLength(fileName); */
String line;
Date[] LAXarray = new Date[getFileCOunt(fileLength)];
int LAXIndex = 0;
try
{
fileStream = new FileInputStream(fileName);
Read = new InputStreamReader(fileStream);
bufRead = new BufferedReader(Read);
line = bufRead.readLine();
for(int i = 1; i < fileLength; i++)
{
line = bufRead.readLine();
LAXarray[i] = processLine(line);
}
}
catch(IOException errorDetails)
{
if(fileStream != null)
{
try
{
fileStream.close();
}
catch(IOException ex2)
{
}
}
System.out.println("Error in fileProcessing: " + errorDetails.getMessage());
}
return LAXarray;
}

reading and writing files java

I have a float array which I stored in it some values from user input.
I have 2 methods one that saves the values stored in the array to a text file each value on a line and the second method rereads the values again and stores them in the array. for example, the user input was 1,2,3,4 I save them to a text file and then I read the same txt file now my array should display 8 elements 1,2,3,4,1,2,3,4.
the problem I'm having is that when I store these elements on the txt file it's storing them and adding like 100 zeros under them and when I'm calling the second method to reread these elements from the file it reads the zeros so when I'm displaying the elements in my array it's displaying 0,0,0,0 when it should display 1,2,3,4,1,2,3,4.
what might be causing me this problem?
public void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file dont exist");
e.printStackTrace();
}
}
public void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
You may check why the array is populated properly using additional println statement. In your version each element of array is populated with the same element read from the file. If you remove the inner loop, array will be populated properly.
int i=0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
System.out.println((i) + "::"+numbers[i]);
i++;
}
Zeros are being added because you're saving numbers as float. If you store an integer 3 in a float variable it will be converted to a float equivalent which is 3.0
Also you don't need two loops here,
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
You can instead do following,
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
Following is a fully functional program of what you desire,
import java.util.Scanner;
import java.io.*;
public class Hello {
public static float[] numbers = {1,2,3,4,1,2,3,4};
public static void saveValuesToFile(Scanner keyboard) {
try {
System.out.println("Enter name of file: ");
String fileName = keyboard.next();
File file = new File(fileName);
PrintWriter outputFile = new PrintWriter(file);
for(int i = 0; i < numbers.length; i++) {
outputFile.println(numbers[i]);
}
outputFile.close();
} catch (FileNotFoundException e) {
System.out.println("file doesn't exist");
e.printStackTrace();
}
}
public static void readFromFile(Scanner keyboard) {
System.out.println("Enter file name");
String fileName = keyboard.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
int i = 0;
while ((input = reader.readLine()) != null) {
numbers[i] = Float.parseFloat(input);
i++;
}
for(int j = 0; j < numbers.length; j++) {
System.out.println(numbers[j]);
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
saveValuesToFile(scanner);
readFromFile(scanner);
}
}

Adding a substring to omit a part of the output

Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc

how can i save the avg to a text file and be printed out

how wold i take the avg of the fallowing program and save the out come to a text file to be printed out
import java.util.Scanner;
public class freethrowpercent {
public static void main(String[] args) {
double freethrowsmade = 1;
double freethrowsmissed = 0;
Scanner input = new Scanner(System.in);
System.out.println("enter 1 if freethorw is made enter 0 for freethrows missed");
freethrowsmade = input.nextDouble() + 1;
freethrowsmissed = input.nextDouble() + 0;
double answer = freethrowsmade / 2 * 100;
System.out.println("percent is" + answer);
}
if that is possable
First, I suggest getting familiar with basic I/O in Java.
If your intention was to write answer to a file, here's one way to do it:
FileWriter writer = null;
try {
String str = Double.toString(answer);
File f = new File("/path/to/file.txt");
writer = new FileWriter(f);
writer.write(str);
} catch (IOException ex) {
} finally {
try {
writer.close();
} catch (IOException ex) {
}
}
}

Reading a file NoSuchElementException [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to read a file with doubles. I locate that problem occurs when I am trying to read decimal numbers. While in case of integers, everything work fine. I am receiving NoSuchElementException exception. Any idea about how to solve my problem? My code:
public class readd {
protected Formatter output;
protected Scanner input = new Scanner(System.in);
private Scanner in = new Scanner(System.in);
protected FileWriter out;
protected BufferedWriter out1;
private String ss;
public int r=1,c=1;
public double[][] output_matrix = null;
public double[][] output_matrix2 = null;
public double[] lap_time = null;
public readd() {
}
public void OpenFileRead(String fileName) { //anoigma tou arxeiou gia diavasma
try {
input = new Scanner(new File(fileName));
System.out.println(fileName);
} catch (FileNotFoundException e) { //sfalma kata tin evresi kai to anoigma tou arxeiou
System.err.println("Sfalma kata to anoigma toy arxeioy");
System.exit(0); //eksodos
}
}
public void Load() { //anagnwsi dedomenwn apo arxeio
// double[][] w1 = null;
int count = 0;
int row = 0, col = 0;
// double [][] w1=null;
try {
while (input.hasNext()) { //oso tha iparxei apothikeumeni eggrafi
count++;
if (count == 1) {
row = input.nextInt();
r = row;
// System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
// System.out.println(col);
c = col;
continue;
} else {
// System.out.println("col="+col);
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
output_matrix[i][j] = input.nextDouble();
//String ss=new Integer(input.nextInt()).toString();
//w1[i][j]=Double.parseDouble(ss.trim());
// String s1 = new Integer(input.nextInt()).toString();
//double v = Double.parseDouble(s1.trim());
//String s2 = new Integer(input.nextInt()).toString();
//int s = Integer.parseInt(s2.trim());
// System.out.print(output_matrix[i][j]+" ");
}
// System.out.println(" ");
}
//System.out.print(col);
//System.out.print(row);
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
}
}
public static void main(String[] args) {
// TODO code application logic here
double[][] wa1;
readd w = new readd();
w.OpenFileRead("W1.txt");
w.Load();
wa1 = w.output_matrix;
}here
I'd also like some more information.
Generally:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/NoSuchElementException.html
It's the end of an enumerator.
There is an idea
Scanner sc = new Scanner("1.0");
sc.nextDouble();
sc.nextDouble();
throws java.util.NoSuchElementException
just as API Scanner.nextDouble says
* #throws NoSuchElementException if the input is exhausted
enter package read;
import java.util.*;
import java.io.File;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileNotFoundException;
/**
*
* #author zenitis
*/
public class readd {
protected Formatter output;
protected Scanner input = new Scanner(System.in);
private Scanner in = new Scanner(System.in);
protected FileWriter out;
protected BufferedWriter out1;
private String ss;
public int r=1,c=1;
public double[][] output_matrix = null;
public double[][] output_matrix2 = null;
public double[] lap_time = null;
public readd() {
}
public void OpenFileRead(String fileName) {
try {
input = new Scanner(new File(fileName));
System.out.println(fileName);
} catch (FileNotFoundException e) {
System.err.println("Sfalma kata to anoigma toy arxeioy");
System.exit(0);
}
}
public void Load() {
int count = 0;
int row = 0, col = 0;
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
continue;
} else if (count == 2) {
col = input.nextInt();
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
output_matrix[i][j] = input.nextDouble();
}
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
}
public static void main(String[] args) {
double[][] wa1;
readd w = new readd();
w.OpenFileRead("W1.txt");
w.Load();
wa1 = w.output_matrix;
}
}here
I dont understand i change dot with comma in my txt file and everything works!!

Categories