Printwriter not writing to file - java

output file is created but numbers are not written.
public static void main(String[] args)
{
String file_name;
String done_string = "done";
boolean done = false;
while (!done)
{
file_name = JOptionPane.showInputDialog("Enter a file name" + " or done to exit: ");
if (file_name.equals(done_string))
{
done = true;
JOptionPane.showMessageDialog(null, "EXITING");
}
else
{
try
{
File file_in = new File(file_name);
Scanner input = new Scanner(file_in);
JOptionPane.showMessageDialog(null, "File " + file_name + " found ");
int[] hold_ints = new int[100];
for (int i = 0; i< 100; i++)
{
hold_ints[i] = input.nextInt();
}
PrintWriter output = new PrintWriter("reverse_ints");
for (int i = 99; i <= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}
output.close();
input.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "File " + file_name + " not found ");
}
}
}
}
}
Program should read a file then create an output file that prints the numbers in the input file in reverse.
Actual results just shows the file but nothing is written in the file.

For-loop condition is wrong, so code in the loop is not run.
I suppose it should be
for (int i = 99; i >= 0; i--)
{
output.print(hold_ints[i]);
output.print(" ");
}

Related

Counting characters in a file

I am writing code that counts the number of characters, words and lines in a .txt file. My sample text file has 21 words, 2 lines, and 114 characters. My program output states there are 21 words, 2 lines and 113 characters. The file is mostly barren and is only meant for testing purposes. In the file is:
This is a test for counter function. Contents are subject to change.
This line tests if the line count is correct.
My program is:
public static void counter(){
String file_name = "input.txt";
File input_file = new File(file_name);
Scanner in_file = null;
int word_count = 0;
int line_count = 0;
int char_count = 0;
String line;
try{
in_file = new Scanner(input_file);
}
catch(FileNotFoundException ex){
System.out.println("Error: This file doesn't exist");
System.exit(0);
}
try{
while(in_file.hasNextLine()){
line = in_file.nextLine();
char_count = char_count + line.length();
String[] word_list = line.split(" ");
word_count = word_count + word_list.length;
String[] line_list = line.split("[,\\n]");
line_count = line_count + line_list.length;
}
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Error: The file format is incorrect");
}
catch(InputMismatchException ex){
System.out.println("Error: The file format is incorrect");
}
finally{
System.out.print("Number of words: ");
System.out.println(word_count);
System.out.print("Number of lines: ");
System.out.println(line_count);
System.out.print("Number of characters: ");
System.out.println(char_count);
in_file.close();
}
}
The correct code for this would be
public void calculateFileCharecteristics(String fileName){
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(filename)))){
String line;
int lineCount = 0;
int totalCharCount = 0;
while((line=bufferedReader.readLine())!=null){
lineCount++;
int charCount = line.split("\n").length;
totalCharCount +=charCount;
}
}
}

search program in txt file java code

I wanna develop java program with following task.
use enter file name and also enter product code. and as result its show all products details
for example.
file data is MLK#milk#expired date 15 may 2016
output will be
this product name is milk with MLK code and will expired in 15 may 2016.
help me thanks...
my code is...
import java.io.*;
import java.util.*;
public class search
{
public static void main( String[] args ) throws IOException
{
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("stationMaster.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
if(line.indexOf(word) != -1)
{
while(file.hasNextLine())
{
String data=file.nextLine();
System.out.println(data);
}
//System.out.println("");
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
if(val == 0)
{
System.out.println("Station does not exist");
break;
}
}
}
}
package main;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String tokens[] = null;
String code, product, date;
try {
FileReader fr = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
tokens = line.split("#");
code = tokens[0];
product = tokens[1];
date = tokens[2];
System.out.println("this product name is " + product
+ " with " + code
+ " code and will expired in"
+ date.substring(12));
line = br.readLine();
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
System.out.println("File not found exception.");
} catch (IOException e) {
System.out.println("IO Eception occered.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.util.*;
public class search
{
public static void main( String[] args ) throws IOException
{
String word = ""; int val = 0;
while(!word.matches("quit"))
{
System.out.println("Enter the word to be searched for");
Scanner input = new Scanner(System.in);
word = input.next();
Scanner file = new Scanner(new File("stationMaster.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
//split the string on # character so that you get code, product name and expiration date separately.
String arr[] = line.split("#");
//check whether the string contains the required string or not
try{
if(arr[0].equalsIgnoreCase(word) || arr[1].equalsIgnoreCase(word)){
//line break
System.out.println();
//split the format 'expiration date 15 may 2016' so that we can use date separately without the heading of 'expiration date'
String dateStrings[] = arr[2].split(" ");
System.out.print("this product name is " + arr[1] + " with " + arr[0] + " code and will expire on ");
System.out.println(dateStrings[2] + " " + dateStrings[3] + " " + dateStrings[4]);
val = 1;
break;
}
else
{
val = 0;
continue;
}
}
catch(IndexOutOfBoundsException indexEx){
val = 0;
continue;
}
}
if(val == 0){
System.out.println("Station does not exist");
break;
}
}
}
}
The above code will search the string that will be read from the file if it contains the word to search or not. It can be product code or product name

An array of string causing my program not to continue to run after an if-else statement - java

I am creating a simple program that gets an input from a user and outputs to .txt file. I have made some changes to my code so that whenever a user enters a variation of 'quit', 'Quit', or 'QUIT' it will break, else it will continue as normal. However when I run and enter data as normal it is not continuing as normal and stopping. Also, how would I display a printline so that when a user does type 'Quit' it would say for example
System.out.println("You have quit!");
My Code
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.nio.file.*;
public class JavaProject {
private static char[] input;
public static void main(String[] args) {
//variables
int hrs, mins;
String gamerName, gamerReport;
int gameCount;
int errorCount;
//Main data storage arrays
String[] gameNames = new String[100];
int[] highScores = new int[100];
int[] minutesPlayed = new int [100];
#SuppressWarnings("resource")
Scanner Scan = new Scanner(System.in);
//formatting for output and input
System.out.println("////// Game Score Report Generator \\\\\\\\\\\\");
System.out.println(" ");
//User enters either their name or quit. Entering a name will move on to next part
for ( ; ; )
{
System.out.print("Enter your Name. If you do not wish to proceed, enter 'Quit' to quit.");
System.out.println(" ");
gamerName = Scan.nextLine();
if ("Quit".equals(gamerName))
{
break;
}
for(int b = 1; b < 100; b++ ) { //this is making the code loop 100 times
//user is given an example of input format
System.out.println("Input Gamer Information " + "Using Format --> Game : Achievement Score : Minutes Played");
System.out.println("FALSE DATA FORMAT WILL CAUSE ERROR");
System.out.println(" ");
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
gamerReport = Scan.nextLine();
String[] splitUpReport = null; // an array of string
//splitUpReport = gamerReport.split(":"); // split the text up on the colon
//gets input, if "quit" then break
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equals("quit"))
{
break;
}
if (gamerReport.equals("Quit"))
{
break;
}
if (gamerReport.equals("QUIT"))
{
break;
}
else
{
splitUpReport = gamerReport.split(":");
}
System.out.println("You have quit!");
}
int i = 0;
//copy data from split text into main data storage arrays
gameNames[i] = splitUpReport[0];
highScores[i] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[i] = Integer.parseInt(splitUpReport[2].trim());
//output to file using a PrintWriter using a FileOutPutStream with append set to true within the printwriter constructor
//
try
{
PrintWriter writer = new PrintWriter(new FileOutputStream("Gaming Report Data", true));
writer.println("Player : " + gamerName);
writer.println();
writer.println("--------------------------------");
writer.println();
String[] report = gamerReport.split(":");
writer.println("Game: " + report[0] + ", score= " +report[1] + ", minutes played= " +report[2]);
//writer.println("Games Played: " + splitUpReport);
//writer.println("Total Achievement: " + highScores);
//writer.println("Total Time: " + minutesPlayedS%60);
writer.println();
writer.close();
} catch (IOException e)
{
System.err.println("File does not exist!");
}
}
}
System.out.println("Goodbye!");
}
public static char[] getInput() {
return input;
}
public static void setInput(char[] input) {
JavaProject.input = input;
}
}
my code issue
//gets input, if "quit" then break
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equals("quit"))
{
break;
}
if (gamerReport.equals("Quit"))
{
break;
}
if (gamerReport.equals("QUIT"))
{
break;
}
else
{
splitUpReport = gamerReport.split(":");
}
System.out.println("You have quit!");
}
You should change your if to else if. Otherwise your else is only regarding the third if. You can also use a single if with equalsIgnoreCase. This matches quit, Quit or QUIT.
To print a message, before each break, insert your System.out.println("You have quit!");
for (int count = 0; count <= 100; count++){
gamerReport = Scan.nextLine();
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
break;
}
splitUpReport = gamerReport.split(":");
gameNames[count] = splitUpReport[0];
highScores[count] = Integer.parseInt(splitUpReport[1].trim() );
minutesPlayed[count] = Integer.parseInt(splitUpReport[2].trim());
}
You also have another option, maybe more in-line with what you were trying to do.
// ignore the for loop
gamerReport = Scan.nextLine();
if (gamerReport.equalsIgnoreCase("quit")) {
System.out.println("You have quit!");
return;
}
splitUpReport = gamerReport.split(":");
You should also not comment one of your scans:
//another data input guide which is just above where data input is in console
System.out.println("Game : Achievement Score : Minutes Played");
//gamerReport = Scan.nextLine();
And your writer should use splitReport:
writer.println("Game: " + splitUpReport[0] + ", score= " + splitUpReport[1] + ", minutes played= " + splitUpReport[2]);

How would I modify this so that rather than have it break it will just request the user to enter the file name again?

The problem
When the user enters the filename into the program, it will create an exception stating that there is no file named like that in the directory.
What I want is that - instead of showing an exception - the program will repeat the message that asks the user to enter the filename.
My code:
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 FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName);
}else{
}
}
}
private static void processFile(String fileName) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).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 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");
}
}
You can try determine if the file exists first by doing something like the following:
File file = new File(fileName);
if(file.exists()) {
processFile(fileName)
}
Here is the solution
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
System.out.println("Enter filename");
String fileName = sc.nextLine();
File file = new File(fileName);
if(!file.exists()) {
continue;
}
processFile(fileName);
}
}
Use this code:
String fileName;
File file;
for(;;) {
/* read file name */
System.out.print("enter file name: ");
fileName = bufferedReader.readLine();
file = new File(fileName);
/* check path */
if (!file.exists())
System.out.println("file doesn't exist");
else if(!file.isFile())
System.out.println("file isn't a regular file");
else if (...)
...
else
break;
}
where bufferedReader is BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); if you want to read file name from keyboard.
You can check if file exists exists(), is a regular file isFile(), is a directory isDirectory(), can be read carRead(), wrote canWrite(), executed canExecute(), an so on..

Outputting to a closed stream?

So I fixed my program but the problem is that after replacing all the blank spaces with tildes i have to output the text to a file that has been closed. How would I re-open the file for output and input something in?
//Name: Allen Li
//Program file: Vowels.Java
//Purpose: Using File IO, read a file's input and output this text to a new text file
//When outputting, all blank spaces will be changed to tildes and there will be a count of each vowel(AEIOU)
import java.util.Scanner; //input
import java.io.File; //IO
import java.io.IOException; //IO exception class
import java.io.FileWriter; //file output
import java.io.FileReader; //file input
import java.io.FileNotFoundException; //if file isnt found, file not found class
public class Vowels { //class
public static void main(String[] args) { //main method
try { //try block
FileReader poetry = new FileReader("poetry.txt");
FileWriter dentist = new FileWriter(
"LI_ALLEN_dentist.txt");
int a;
while ((a = poetry.read()) != -1) {
dentist.write(a);
System.out.print((char) a); //print the file to the monitor
}
poetry.close();
dentist.close();
Scanner inFile = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
int numOfVowelsA = 0; //count #s of A/E/I/O/U vowels
int numOfVowelsE = 0;
int numOfVowelsI = 0;
int numOfVowelsO = 0;
int numOfVowelsU = 0;
while (inFile.hasNext()) {
String sentence = inFile.next() /* ("\\S+") */;
for (int i = 0; i <= sentence.length() - 1; i++) {
if (sentence.toLowerCase().charAt(i) == 'a') {
numOfVowelsA++;
}
if (sentence.toLowerCase().charAt(i) == 'e') {
numOfVowelsE++;
}
if (sentence.toLowerCase().charAt(i) == 'i') {
numOfVowelsI++;
}
if (sentence.toLowerCase().charAt(i) == 'o') {
numOfVowelsO++;
}
if (sentence.toLowerCase().charAt(i) == 'u') {
numOfVowelsU++;
}
}
}
System.out.println();
System.out.println("There are " + numOfVowelsA
+ " A vowels in this file of text");
System.out.println("There are " + numOfVowelsE
+ " E vowels in this file of text.");
System.out.println("There are " + numOfVowelsI
+ " I vowels in this file of text.");
System.out.println("There are " + numOfVowelsO
+ " O vowels in this file of text.");
System.out.println("There are " + numOfVowelsU
+ " U vowels in this file of text. ");
Scanner tildes = new Scanner(new File(
"LI_ALLEN_dentist.txt"));
while (tildes.hasNext()) {
String replace = tildes.nextLine();
replace = replace.replaceAll(" ", "~");
System.out.println();
System.out.print(replace);
}
} catch (FileNotFoundException i) {
System.out.println("The file you are trying to use as input is not found. " + i);
} catch (IOException i) {
System.out.println("There is an issue with the input or output file. " + i);
}
}
}
You didn't close inFile. Close inFile first and then you are able to open it again in tildes.
Close it before Scanner tildes = new Scanner(...); line.

Categories

Resources