Adding text at the beginning of a file Java - java

This is a project for school, and I am having difficulty figuring out why it is this way. We are to create a program that will put data into a text file, but whenever I run my code, it will output to the file, but it will be at line 224, and not start at the beginning. Does anyone know why this may be? Here is my code
import java.nio.file.*;
import java.io.*;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.nio.channels.FileChannel;
public class CreateCustomerFile
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Path file = Paths.get("C:\\Users\\brady\\IdeaProjects\\TestNew\\Customers.txt");
String s = "000, ,00000" + System.getProperty("line.separator");
String[] array;
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
FileChannel fc = null;
final int recordSize = s.length(); //Size of record
final int recordNums = 1000; //Number of records stored in file
final String QUIT = "exit";
String custString;
int custNum;
String lastName;
String zipCode;
String fileNum;
try
{
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
for(int count = 0; count < recordNums; ++count)
writer.write(s, 0, s.length());
writer.close();
}
catch(Exception e)
{
System.out.println("Error message: " + e);
}
try
{
fc = (FileChannel)Files.newByteChannel(file, READ, WRITE);
System.out.print("Enter customer number or 'exit' to quit >> ");
custString = input.nextLine();
while(!(custString.equalsIgnoreCase(QUIT)))
{
custNum = Integer.parseInt(custString);
buffer = ByteBuffer.wrap(data);
fc.position((long) custNum * recordSize);
fc.read(buffer);
s = new String(data);
array = s.split(",");
fileNum = array[0];
if(!(fileNum.equals("000")))
System.out.println("Sorry - customer " + custString + " already exists");
else
{
System.out.print("Enter the last name for customer #" + custNum + ": ");
lastName = input.nextLine();
StringBuilder sb = new StringBuilder(lastName);
sb.append(" ");
sb.setLength(6);
lastName = sb.toString();
System.out.print("Enter zip code: ");
zipCode = input.nextLine();
s = custString + "," + lastName + "," + zipCode + System.getProperty("line.separator");
data = s.getBytes();
buffer = ByteBuffer.wrap(data);
fc.position((long) custNum * recordSize);
fc.write(buffer);
}
System.out.print("Enter next customer number or 'exit' to quit: ");
custString = input.nextLine();
}
fc.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
}

Your code needs more input validation, any user provided string input must be sized for the output field, no matter the input.
lastName is done correctly, but customer number and zip code are left to chance, and can throw off the record count in the file.
A customer id entered as "1" is 2 characters shorter than "001" thus upsetting the fixed length record for the remaining file.

Related

I'm using BufferedReader to input string values into the Excel file but in the next iteration it's skipping the entry of the first string

This is the code I have written. It works fine when I use Scanner but doesn't work properly with BufferedReader.
This is the Question
Develop and test a program according to the following specification.
Consider a class Student with instance fields name, registration number and CGPA.
Enter information about twenty such students through keyboard into an Excel file.
Sort the records of the file in order of registration number.
Split the content of the file into two halves and write each half to an Excel file.
Code:
package com.hitesh;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Student {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("DA3.xls");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
String registrationNo;
float gpa;
int n = 0;
Scanner scanner = new Scanner(System.in);
fw.write("Student Name" + '\t' + "Registration No" + '\t' + "GPA" + '\n');
while (n < 3)
{
System.out.print("Enter Student Name: ");
name = br.readLine();
// name = scanner.next();
System.out.print("Enter registration number: ");
registrationNo = br.readLine();
// registrationNo = scanner.next();
System.out.print("Enter GPA: ");
gpa = br.read();
// gpa = scanner.nextFloat();
fw.write(name + '\t' + registrationNo + '\t' + gpa + '\n');
n++;
}
fw.close();
}
}
Output Screenshot
Your code works fine for me – JDK 11 on Windows 10 – after I changed this line of your code:
gpa = br.read();
to this:
gpa = br.readLine();
According to the javadoc for method read, in class java.io.BufferedReader:
Reads a single character.
The newline in Windows is actually two characters so you are actually just reading one character in the last part of the while loop and ignoring the newline characters which messes up the first readLine call in the beginning of the next iteration of the while loop.
Here is the complete code.
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class Student {
public static void main(String[] args) throws IOException {
try (FileWriter fw = new FileWriter("DA3.xls");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr)) {
fw.write("Student Name" + '\t' + "Registration No" + '\t' + "GPA" + '\n');
int n = 0;
while (n < 3) {
System.out.print("Enter student name: ");
String name = br.readLine();
System.out.print("Enter registration number: ");
String registrationNo = br.readLine();
System.out.print("Enter GPA: ");
String gpa = br.readLine();
fw.write(name + "\t" + registrationNo + "\t" + gpa + "\n");
n++;
}
}
}
}
And Excel correctly displays the file – after it shows me a dialog window with a message that the file format is not suitable and asks me whether I still want to open the file. I say yes and the data written to the file in the Java program is correctly displayed. Of-course Excel guesses how to display the data which meant that it did not display the GPA correctly. In order to create a correctly formatted Excel file from Java, you need to use a library like Apache POI.
I would Scanner as you planned:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("DA3.csv");
final String FMT = "%s\t%s\t%s%n";
String name;
String registrationNo;
float gpa;
int n = 0;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\R");
fw.write(String.format(FMT, "Student Name", "Registration No", "GPA"));
while (n < 3) {
System.out.print("Enter Student Name: ");
name = scanner.next();
System.out.print("Enter registration number: ");
registrationNo = scanner.next();
System.out.print("Enter GPA: ");
gpa = scanner.nextFloat();
fw.write(String.format(FMT, name, registrationNo, gpa));
n++;
}
fw.close();
}

Display error when empty array

I am creating a reverse polish notation calculator in java that accepts file input. One of the requirements is that certain statistics are generated from the calculations too.
below are two snippets of my code.
public static int invalidlines = 0;
public static int validlines = 0;
public static int stats1 = 0;
private static Scanner input;
public static ArrayList<String> validList = new ArrayList<String>();
public static ArrayList<Integer> stats = new ArrayList<Integer>(); {
if (stats.isEmpty());
display("n/a");
}
static int sum(ArrayList<Integer> stats)
{
int value = 0;
for(int i : stats)
{
value += i;
}
return value;
}
Thats the code for my array lists.
static void fileInput() throws IOException
{
input = new Scanner(System.in);
try
{
String currentLine = new String();
int answer = 0;
//Open the file
display("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(strLine.trim().isEmpty())
{
display("You have entered a blank line, the program will now exit");
System.exit(0);
}
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
display("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
stats.add(answer);
break;
case("-"):
answer = val1 - val2;
stats.add(answer);
break;
case("/"):
answer = val1 / val2;
stats.add(answer);
break;
case("*"):
answer = val1 * val2;
stats.add(answer);
break;
}
display("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
display("Please Enter a valid file name");
}
display("Evaluations Complete");
display("=====================");
display("Highest Result: " + Collections.max(stats));
display("Lowest Result: " + Collections.min(stats));
display("Aggregate Result: " + sum(stats));
display("Average Result: " + sum(stats) / validlines);
display("Total Valid Lines: " + validlines);
display("Total Invalid Lines: " + invalidlines);
}
I require it so that if there are no valid calculations from the text file that the highest, lowest and average result displays show as 'n/a' instead they bring the java error in my console shown below.
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(Unknown Source)
at java.util.Collections.max(Unknown Source)
at Assignment.fileInput(Assignment.java:156)
at Assignment.main(Assignment.java:177)
Replace
Collections.max(stats)
with
(!stats.isEmpty() ? Collections.max(stats) : "n/a")
(similarly for Collections.min)
You are also going to want to handle the case of validlines == 0 to avoid the division by zero error in / validlines.

symbol not found of method

I am doing this Java assignment for class, and for some reason this method keeps saying the symbol can not be found. The block of code below is what gave me the error. Not entirely sure as to why because I followed the book verbatim and there was no mention of it compiling with an error (usually there is an indication to look for that)
I added the rest of the assignment to the post. I wasnt sure if it was relative or not because I was getting the error before I wrote the second half of this that is being posted now. I'm not sure if the error has to do with calling the methods before the method is actually defined, but i tried switching the order and it did not make a difference when I compiled it.
import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
public class CreateFilesBasedOnState
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Path inStateFile = Paths.get("InStateCusts.txt");
Path outOfStateFile = Paths.get("OutofStateCusts.txt");
final String ID_FORMAT = "000";
final String NAME_FORMAT = " ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String HOME_STATE = "WI";
final String BALANCE_FORMAT = "0000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_FORMAT + delimiter
+ HOME_STATE + delimiter + BALANCE_FORMAT
+ System.getProperty("line.seperator");
final int RECSIZE = s.length();
FileChannel fcIn = null;
FileChannel fcOut = null;
String idString;
int id;
String name;
String state;
double balance;
final String QUIT = "999";
createEmptyFile(inStateFile, s);
createEmptyFile(outOfStateFile, s);
try
{
fcIn = (FileChannel) Files.newByteChannel(inStateFile,
CREATE,
WRITE);
fcOut = (FileChannel) Files.newByteChannel(outOfStateFile,
CREATE,
WRITE);
System.out.print("Enter customer account number >> ");
idString = input.nextLine();
while (!(idString.equals(QUIT)))
{
id = Integer.parseInt(idString);
System.out.print("Enter name for customer >> ");
name = input.nextLine();
StringBuilder sb = new StringBuilder(name);
name = sb.toString();
System.out.print("Enter state >> ");
state = input.nextLine();
System.out.print("Enter balance >> ");
balance = input.nextDouble();
input.nextLine();
DecimalFormat df = new DecimalFormat(BALANCE_FORMAT);
s = idString + delimiter + name + delimiter + state
+ delimiter + df.format(balance)
+ System.getProperty("line.separator");
byte[] data = s.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(data);
if (state.equals(HOME_STATE))
{
fcIn.position(id * RECSIZE);
fcIn.write(buffer);
}
else
{
fcOut.position(id * RECSIZE);
fcOut.write(buffer);
}
System.out.print( "Ener next cusomter account number or "
+ QUIT + " to quit >> ");
idString = input.nextLine();
}
fcIn.close();
fcOut.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
public static void createEmtpyFile(Path file, String s)
{
final int NUMRECS = 1000;
try
{
OutputStream outputStr
= new BufferedOutputStream(Files.newOutputStream(file
, CREATE));
BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(outputStr));
for (int count = 0; count < NUMRECS; ++count) {
writer.write(s, 0, s.length());
}
writer.close();
}
catch (Exception e)
{
System.out.println("Error message: " + e);
}
}
}

Why won't the BufferedWriter instantiation write to a txt file in Java?

I am trying to instantiate a object with BufferedWriter and it wont work. The problem happens when I use the write function. Why won't it let me write to the file?
The error is cannot find symbol. Please help me. I know someone knows. Why wont it not find the symbol when this is a bufferedWriter method?
package ex5_abcd;
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class EX5_ABCD {
public static void main(String[] args) {
boolean go = true;
String firstN, lastN;
String lineWritten = "";
int IdNum;
Scanner input = new Scanner(System.in);
Path file = Paths.get("C:\\Java\\empList.txt");
try {
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
while (go) {
System.out.println("Please enter Employee's First Name");
firstN = input.nextLine();
System.out.println("Please enter Employee's Last Name");
lastN = input.nextLine();
System.out.println("Please enter " + firstN + " " + lastN);
IdNum = input.nextInt();
lineWritten = IdNum + " " + firstN + " " + lastN;
int lineLength = lineWritten.length();
char [] testChar = new char[1];
testChar [0] = 'a';
writer = write(testChar, 0, lineLength); // Why write error
writer.flush();
writer.newLine();
}
writer.close();
} catch (Exception e) {
System.out.println("Error Msg:" + e);
}
}
}
writer = write(lineWritten, 0, lineLength);
should be rewritten to
writer.write(lineWritten, 0, lineLength);
since writer is not a reference to an object, you should call the method of the writer object, not set writer to another value
Recap:
(=) sets a value.
Also, since you never set the value of go as false in your loop, you will keep on looping there... forever... and ever.... I suggest to not let that happen

Possible to write what would be output into a HTML file?

What I want to do is make it so that when the program runs it will run the ordinary way but if the user selects that they want the display to be in html then it will run what the ordinary program would do but rather than display it in the console it will write what was going to appear in the console into a html file that the user specifies. Is this possible? I have code to accept the user input and have them specify what format they want it in as well as open the browser but I'm not sure if this could work. The code I have already is below:
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
// Used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
// Checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
// Also checks to make sure that there are no results that are just whitespace
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (Exception e) {
return false;
}
}
// Checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (true) { // Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if (!file.exists()) {
continue;
}
if (UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("H")) {
Desktop.getDesktop().browse(file.toURI());
} else if (input.equalsIgnoreCase("T")) {
processFile(UserFile);
} else {
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
// Checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
// Splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
// Output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
// Displays the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
//This is where we'll write the HTML to if the user's chooses so
private static final String OUTPUT_FILENAME = "output.html";
public static void main(String[] args) throws IOException
{
final Scanner scanner = new Scanner(System.in);
final String content = "Foobar";
final boolean toHtml;
String input;
//Get the user's input
do
{
System.out.print("Do you want messages "
+ "written to (P)lain text, or (H)TML? ");
input = scanner.nextLine();
} while (!(input.equalsIgnoreCase("p")
|| input.equalsIgnoreCase("h")));
toHtml = input.equalsIgnoreCase("h");
if (toHtml)
{
//Redirect the standard output stream to the HTML file
final FileOutputStream fileOut //False indicates we're not appending
= new FileOutputStream(OUTPUT_FILENAME, false);
final PrintStream outStream = new PrintStream(fileOut);
System.setOut(outStream);
}
System.out.println(toHtml
? String.format("<p>%s</p>", content) //Write HTML to file
: content); //We're not writing to an HTML file: plain text
}

Categories