Saving the result to file - JAVA - java

I have a very stupid problem... I cannot get know how to save the results in output file that second array is save in a lower line.
This is how it saves:
dist[0 10 13 10 6 18 ] pred[-15 2 5 1 4 ]
I want it to save like this:
dist[0 10 13 10 6 18 ]
pred[-15 2 5 1 4 ]
CODE:
try{
outputFile = new File("Out0304.txt");
out = new FileWriter(outputFile);
out.write("\n" + "dist[");
out.write("\n");
for (Top way : tops){
out.write(way.shortest_path + " ");
}
out.write("]\n");
out.write("\n");
out.write("\n" + "pred[");
for (Top ww : tops){
if (ww.previous != null) {
out.write(ww.previous.number + " ");
}
else{
out.write("-1");
}
}
out.write("] \n ");
out.close();
}
catch (IOException e){
System.out.println("Blad: " + e.toString());
}
}
}

In Windows you need "\r\n" for new line

You can use the following to write to file:
PrintWriter pw = new PrintWriter(new FileWriter("fileName"),true);
pw.println("[");
for(int i=0;i<pred.length;i++)
{
pw.println(pred[i]+" ");
}
pw.println("]");
pw.close();

Related

java.io.EOFException being thrown

This code is throwing an java.io.EOFException, and I am not sure why this is happening.
import java.io.*;
class ReadInts {
public static void main(String[] args) {
String fileName = "intData.dat";
int sum = 0;
try {
DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
while (true) {
sum += instr.readInt();
System.out.println("The sum is: " + sum);
sum += instr.readInt();
System.out.println("The sum is: " + sum);
sum += instr.readInt();
System.out.println("The sum is: " + sum);
sum += instr.readInt();
System.out.println("The sum is: " + sum);
instr.close();
}
} catch (EOFException e) {
System.out.println("EOF reached for: " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File " + fileName + " not found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Problem reading " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
The contents of the input file is:
0
1
255
-1
There is no return character of line feed after -1.
The output I receive is:
The sum is: 805974282
The sum is: 1648322068
EOF reaced for: intData.dat
null
java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at ReadInts.main(ReadInts.java:18)
The output is completely unexpected, and I assume the exception is being thrown because, for whatever reason, the value of sum is great than the maximum value of an int.
I tried changing "int sum = 0" to "long sum = 0" and received the same results.
I commented out the following:
sumOfInts += instr.readInt();
System.out.println("The sum is: " + sumOfInts);
sumOfInts += instr.readInt();
// System.out.println("The sum is: " + sumOfInts);
// sumOfInts += instr.readInt();
// System.out.println("The sum is: " + sumOfInts);
// sumOfInts += instr.readInt();
After doing this, I received the following exception:
The sum is: 805974282
The sum is: 1648322068
Problem reading intData.dat
Stream closed
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:269)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at ReadInts.main(ReadInts.java:14)
If it helps, I am using Ubuntu 18.04 LTS.
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Thanks for any help.
Tony
The problem is that readInt is not reading a string and convert the string to a number; it
reads four input bytes and returns an int value which it calculates using binary arithmetic.
0, \n(13), 1, \n(13) is 1st readInt
2, 5, 5, \n(13) is 2nd readInt
2 is third readInt after which you will get EOF exception
One more suggestion would be to close objects like stream in finally block
public static void main(String[] args) throws Exception {
String fileName = "C:\\rsc\\intdat.dat";
int sum = 0;
DataInputStream instr=null;
try {
instr = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
while (instr.available()!=0) {
sum += Integer.parseInt(instr.readLine());
System.out.println("The sum is: " + sum);
}
} catch (EOFException e) {
System.out.println("EOF reached for: " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File " + fileName + " not found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Problem reading " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
}
finally{
if(instr!=null)
instr.close();
}
}
PS: InputStream is a binary construct. If you want to read text data use BufferedReader instead
DataInputStream reads input as bytes in chunk of 4.
So,
0
1
255
-1
0, \n, 1, \n is one readInt
2, 5, 5, \n is other readInt
-1 is third readInt
So, after three readInt, you will get EOF exception as file has been finished.
Also, you should correct out wile loop.

JavaFX InputMismatchException - Label from Scanner

problems will be there cause i want make Labels from text file and then put it into VBOX and i getting inputmismatchexception and it dont make new Object
VBox vertikalBox = new VBox();
try (Scanner s = new Scanner("rebricek.txt")) {
while (s.hasNext()) {
//InputMismatchException
vertikalBox.getChildren().addAll(new Label(""+ s.nextInt() + " " + s.next() + " " + s.nextInt()));
s.nextLine();
}
} catch (Throwable t) {
// inputmismatchexception - PROBLEM
// this is for NoSuchElementException
System.err.println("Vyskytla sa chyba pri praci zo suborom");
}
FILE content :
1 nikto 10
2 nikto 0
3 nikto 0
4 nikto 0
5 nikto 0
6 nikto 0
7 nikto 0
8 nikto 0
9 nikto 0
10 nikto 0
Your scanner is reading the string "rebrickek.txt" not a file
File file = new File("rebricek.txt");
if(file.exist())
{
Scanner s = new Scanner(file);
.
.
.
}
else
{
System.out.println("The file does note exist!");
}

Array Index Out Of Bounds Exception Issue

I'm currently receiving an out of bounds issue in my array and I'm really unsure where exactly I've went wrong here. I'm really looking for a second pair of eyes over this thing as I'm going to lose my mind.
I honestly appreciate any help given.
No really: Thanks.
package com.jpmorgan.spring.csv;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVRead {
static void read() throws IOException {
String csvFileToRead = "profit.csv";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
String[] array = line.split(splitBy);
System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name=" + array[1] + " , Quantity=" + array[2]
+ " , Buy=" + array[3] + " , Sell=" + array[4] + /*" , Coupon=" + array[5] +*/ "]");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done reading CSV file");
}
}
This is the full CSV file.
I've tried using debug but it's not been much help.
instrument_type,name,quantity,buy_price,sell_price,coupon
Equity,AAA,123,1.01,1.10
Equity,BBBB,3,1.05,1.01
Bond,CCC,3,,,0.13
Equity,AAA,12,1.11,1.13
Bond,DD,3,,,1.24
Main class for reference.
/**
* Main class is menu driven, receives CSV input.
* This program reads, calculates and writes CSV files.
* #author David McNeill
* #version 1.0 - 17/03/1015
*/
package com.jpmorgan.spring.csv;
import java.util.Scanner;
public class CSVMain{
public static void main(String[] arg) throws Exception {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.println("Please choose an option using 1 - 4"); //print text to screen
System.out.println("------------------------------------"); //print text to screen
System.out.println("1: Read 'input' CSV file"); //print text to screen
System.out.println("2: Calculate 'input' CSV file"); //print text to screen
System.out.println("3: Write calculation result to CSV file"); //print text to screen
System.out.println("4: Exit program"); //print text to screen
userChoice = in.nextInt(); //'in' equals integer
if (userChoice == 4) //when '3' is input then...
quit = true; //the program will now quit
else if (userChoice == 1) //when '1' is input then...
CSVRead.read();
else if (userChoice == 2);
//####################calculations go here#########################
//####################calculations go here#########################
//####################calculations go here#########################
else if (userChoice == 3)
CSVWrite.write();
} while (!quit);
}
}
After splitting the line you should make sure you're getting the right number of columns.
I can't tell you how to fix the potentially bad data but I can help you identify it. Just replace the inner loop with this:
int lineNum = 0;
while ((line = br.readLine()) != null) {
String[] array = line.split(splitBy);
if (array.length < 5)
throw new Exception("There's a problem with " + csvFileToRead + " on line " + lineNum + ":\n" + line);
System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name=" + array[1] + " , Quantity=" + array[2]
+ " , Buy=" + array[3] + " , Sell=" + array[4] + /*" , Coupon=" + array[5] +*/ "]");
lineNum++;
}
your CSVRead has no main method.. change the call to CSVRead.read();
import java.util.Scanner;
public class CSVMain{
public static void main(String[] arg) throws Exception {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.println("Please choose an option using 1 - 4"); //print text to screen
System.out.println("------------------------------------"); //print text to screen
System.out.println("1: Read 'input' CSV file"); //print text to screen
System.out.println("2: Calculate 'input' CSV file"); //print text to screen
System.out.println("3: Write calculation result to CSV file"); //print text to screen
System.out.println("4: Exit program"); //print text to screen
userChoice = in.nextInt(); //'in' equals integer
if (userChoice == 4) //when '3' is input then...
quit = true; //the program will now quit
else if (userChoice == 1) //when '1' is input then...
CSVRead.read();
else if (userChoice == 2);
//####################calculations go here#########################
//####################calculations go here#########################
//####################calculations go here#########################
} while (!quit);
}
}
CSVRead.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVRead {
static void read() throws IOException {
String csvFileToRead = "profit.csv";
BufferedReader br = null;
String line = "";
String splitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFileToRead));
while ((line = br.readLine()) != null) {
String[] array = line.split(splitBy);
System.out.println("Equity & Bonds: [Instrument Type= " + array[0] + " , Name=" + array[1] + " , Quantity=" + array[2]
+ " , Buy=" + array[3] + " , Sell=" + array[4] + /*" , Coupon=" + array[5] +*/ "]");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done reading CSV file");
}
}
OUTPUT
Please choose an option using 1 - 4
------------------------------------
1: Read 'input' CSV file
2: Calculate 'input' CSV file
3: Write calculation result to CSV file
4: Exit program
1
Equity & Bonds: [Instrument Type= instrument_type , Name=name , Quantity=quantity , Buy=buy_price , Sell=sell_price]
Equity & Bonds: [Instrument Type= Equity , Name=AAA , Quantity=123 , Buy=1.01 , Sell=1.10]
Equity & Bonds: [Instrument Type= Equity , Name=BBBB , Quantity=3 , Buy=1.05 , Sell=1.01]
Equity & Bonds: [Instrument Type= Bond , Name=CCC , Quantity=3 , Buy= , Sell=]
Equity & Bonds: [Instrument Type= Equity , Name=AAA , Quantity=12 , Buy=1.11 , Sell=1.13]
Equity & Bonds: [Instrument Type= Bond , Name=DD , Quantity=3 , Buy= , Sell=]
Done reading CSV file
ALTERNATIVELY, rename read method to main in CSVRead
class public class CSVRead {
static void main() throws IOException {
then call it like you do CSVRead.main(); in CSVMain class

Error when reading from text file

I keep getting this error when reading from a text file it gets the first few numbers but then does this there also shouldnt be 0's in there, tried a lot of things not sure what to do. I have to be able to read the file numbers and then multiply specific ones could use some help thanks. (I was using the final println to check what numbers it was getting). Sorry forgot the error is this output
4
32
0
38
0
38
0
16
0
Error: For input string: ""
Here is my file:
Unit One
4
32 8
38 6
38 6
16 7
Unit Two
0
Unit Three
2
36 7
36 7
Unit Four
6
32 6.5
32 6.5
36 6.5
36 6.5
38 6.5
38 6.5
Unit Five
4
32 6.5
32 8
32 7
32 8
Unit Six
5
38 7
30 6.5
24 8
24 8
24 8
Unit Seven
0
Unit Eight
1
40 12
Unit Nine
5
24 8
24 6.5
30 6.5
24 7
32 7
And here is my code:
package question;
import java.io.*;
import java.util.Scanner;
public class Weight
{
public static void main(String[] args)//main method
{
try
{
Scanner input = new Scanner(System.in);
//System.out.print("Please enter proposed weight of stock : ");
// int proposedWeight = input.nextInt();
File file = new File("MathUnits.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null)
{ int i = 0;
if (strline.contains("Unit"))
{
continue;
}
else {
String[] numstrs = strline.split("\\s+"); // split by white space
int[] nums = new int[numstrs.length];
nums[i] = Integer.parseInt(numstrs[i]);
for(int f = 0; f <numstrs.length; f++)
{
System.out.println(""+ nums[f]);
}
}
i ++;
}
//int x = Integer.parseInt(numstrs[0]);
// int m = Integer.parseInt(numstrs[1]);
// int b = Integer.parseInt(numstrs[2]);
// int a = Integer.parseInt(numstrs[3]);
int a = 0;
// System.out.println("this >>" + x + "," + m +"," + b + "," + a);
// if(proposedWeight < a)
// {
// System.out.println("Stock is lighter than proposed and can hold easily");
// System.exit(0);
// }
// else if ( a == proposedWeight)
// {
// System.out.println("Stock is equal to max");
// System.exit(0);
// }
// else
// {
// System.out.println("stock is too heavy");
// System.exit(0);
// }
in.close();
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
One probable error I see
You're not taking newlines into consideration, especially when you're doing a nums[i] = Integer.parseInt(numstrs[i]); on an empty string
Also, I don't think you're getting the numbers into the array correct since you're getting only one int from each line, when some lines have two

File Input Java Mac

I'm writing up a program that goes into a basic .txt file and prints certain things. It is a comma-delimited file. The file includes 7 first and last names, and also 4 numbers after. Each of the seven on a separate line.
Each line looks like this:
George Washington, 7, 15, 20, 14
The program has to grab the last name and then average the 4 numbers, but also average the first from all seven, second from all seven, etc. I'm not sure on how to start approaching this and get it to keep grabbing and printing what's necessary. Thanks for any help. I appreciate it. I'm using a Mac to do all of this programming and it needs to run on Windows so I'm using :
File Grades = new File(System.getProperty("user.home"), "grades.txt");
so how would I use that to read from the file?
Java's File class doesn't actually handle the opening or reading for you. You may want to look at the FileReader and BufferedReader classes.
Don't worry about whether it's running on Mac or Windows. Java takes care of all the business for you. :)
You could do something like the following. It's just a quick solution so you might want to do some changes perhaps. It reads from a file named "input.txt" right now.
import java.io.*;
public class ParseLines {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("input.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(new DataInputStream(fs)));
String line;
double collect[] = {0.0, 0.0, 0.0, 0.0};
int lines = 0;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 5) {
int avg = 0;
boolean skip = false;
for (int i = 1; i < 5; i++) {
String part = parts[i].trim();
try {
int num = Integer.valueOf(part);
avg += num;
collect[i - 1] += (double) num;
}
catch (NumberFormatException nexp) {
System.err.println("Input '" + part +
"' not a number on line: " + line);
skip = true;
break;
}
}
if (skip) continue;
avg /= 4;
lines++;
System.out.println("Last name: " + parts[0].split(" ")[1] +
", Avg.: " + avg);
}
else {
System.err.println("Ignored line: " + line);
}
}
for (int i = 0; i < 4; i++) {
collect[i] /= (double) lines;
System.out.println("Average of column " + (i + 1) + ": " +
collect[i]);
}
reader.close();
} catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Edit: Altered the code to average the first, second, third and fourth column.

Categories

Resources