Outputting to a closed stream? - java

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.

Related

Printwriter not writing to file

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(" ");
}

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

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..

Output is not coming out correctly

The goal of this code is to read a file and add numbers to the end of every {(curly bracket) but the file does not output each line like it does in the file but it out puts it into one entire line. where do I put a System.out.println statement. I tried every where and it keeps repeating it
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
readFile();
}
public static void readFile() { // Method to read file
Scanner inFile = null;
String out = " ";
try {
Scanner input = new Scanner(System.in);
System.out.println("enter file name");
String filename = input.next();
File in = new File(filename); // ask for the file name
inFile = new Scanner(in);
int count = 0;
while (inFile.hasNextLine()) { // reads each line
String line = inFile.nextLine();
for (int i = 0; i < line.length(); i++) {
char ch = line.charAt(i);
out = out + ch;
if (ch == '{') {
count = count + 1;
out = out + " " + count + " ";
} else if (ch == '}') {
out = out + " " + count + " ";
if (count > 0) {
count = count - 1;
}
}
}
}
System.out.println(out);
} catch (FileNotFoundException exception) {
System.out.println("File not found.");
}
inFile.close();
}
}
where do I put a System.out.println statement
The entire output is built in a single string that is not printed until the end, so adding System.out.println statements in the line loop won't help. You can add line breaks to the string by doing:
out += "\n";
Or, at the end of the body of your line loop, print the current line, and reset the buffer for the next line:
System.out.println(out);
out = "";
Using a String for the output buffer is not efficient by the way. String is immutable, so every + statement is copying and duplicating all of the previous characters to create a new object, every time. Consider declaring out as a StringBuilder rather than a String. Then you can add to it with the .append() method and it will not copy all the text every time because a StringBuilder is mutable.

How to resolve '.class' expected error? [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 3 years ago.
Currently I have an error - '.class' expected - on line 40. Any help is hugely appreciated.
import java.io.*; // For File class and FileNotFoundException
import java.util.Scanner; //For the Scanner class
import javax.swing.JOptionPane; // For the JOptionPane class
/**
* Write a description of class PartB here.
*
* #Hubble, Kieran
* #Version 0.1
*/
public class PartB
{
public static void main(String[] args) throws FileNotFoundException
{
File file; //for file input
Scanner inputFile; //for file input
String fileName; //to hold a file name
String paragraph; //to extract the letter frequencies
//get a file name from the user.
fileName = JOptionPane.showInputDialog("enter " + " the name of the file");
//attempt to open the file.
try
{
file = new File(fileName);
inputFile = new Scanner(file);
JOptionPane.showMessageDialog(null, "the file was found.");
// read the input file, processing data one line at a time
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println(str);
}
//create an Output file
PrintWriter outputFile = new PrintWriter("crackedcode.txt");
while(paragraph.length() > 0)
// error is occurring on the next line (line 40)
int[]; letterCount = new int[26];
for (int count = 0; count < paragraph.length; count++) {
String current = paragraph[count];
char[] letters = current.toCharArray();
}
for (int count2 = 0; count2 < letters.length; count2++) { char lett = letters[count2]; if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
// close the input file
inputFile.close();
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "file not found.");
}
JOptionPane.showMessageDialog(null, "done.");
System.exit(0); //terminate program
}
}
Remove the semicolon
int[]; letterCount = new int[26];
should be
int[] letterCount = new int[26];
Also, You need to wrap the block of the while (from the line above it) with {}

Categories

Resources