Why is my FileReader not outputting codes from the .txt file? - java

Sorry If I have any errors because this is my first time asking a question. So basically, my program is converting white_space to underscore and I made it to work. But the problem is, I can't seem to output the inside of my outputfile.txt in the last part of my program.
There should be a premade inputfile.txt for it to work.
Full code:
https://pastebin.com/ecGGd1Z5
Here's the code I'm that's getting problem,
//READING2 No output :(
FileReader yo = new FileReader ("outputfile.txt");
int a;
System.out.println("Outputing from outputfile.txt file ...");
while((a=yo.read())!=-1)
{
System.out.print((char)a);
}
System.out.println("\n");
yo.close();
//

You are not handling the resources correctly. Please find a working example bellow.
It uses "try with resource" so the resource e.g. a FileWriter will be closed correctly:
public class Working {
public static void main(String[] args) throws FileNotFoundException, IOException {
String str;
Scanner scan = new Scanner(System.in);
System.out.println("[Enter source file name: ]");
String input = scan.nextLine();
try (FileReader fread = new FileReader(input)) {
BufferedReader bread = new BufferedReader(fread);
try (FileWriter fwrite = new FileWriter("outputfile.txt")) {
System.out.println(" ");
System.out.println("Creating output file ...");
System.out.println("Output file successly created!");
System.out.println("[Output file name is outputfile.txt]");
System.out.println("=====================");
//READING
FileReader fr = new FileReader(input);
int i;
System.out.println("Outputing from " + input + " file ...");
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
System.out.println("\n");
fr.close();
//
System.out.println("===========");
System.out.println("Starting to convert spaces to underscore ...");
System.out.println("Success!");
System.out.println("===========");
//
while ((str = bread.readLine()) != null) {
str = str.trim();
str = str.replaceAll(" ", "_");
fwrite.write(str);
}
}
//
//READING2 No output :(
try (FileReader yo = new FileReader("outputfile.txt")) {
int a;
System.out.println("Outputing from outputfile.txt file ...");
while ((a = yo.read()) != -1) {
System.out.print((char) a);
}
System.out.println("\n");
}
}
}
}

Related

How to create vcard with own datas in Java?

I'm doing a phonebook and I'd like to save contacts to vcard. I found vcard format on the internet, but I do not know how to read datas from stdin.
package homework;
import java.io.*;
public class SaveToVcard {
public static void vcard() throws IOException {
File file = new File("contact.vcf");
FileOutputStream fop = new FileOutputStream(file);
if (file.exists()) {
String vcard = "BEGIN:VCARD\n" + "VERSION:4.0\n" + "N:Gump;Forrest;;;\n" + "FN:Forrest Gump\n"
+ "ORG:Bubba Gump Shrimp Co.\n" + "TITLE:Shrimp Man\n"
+ "TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212\n"
+ "TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212\n" + "EMAIL:forrestgump#example.com\n"
+ "REV:20080424T195243Z\n" + "END:VCARD";
fop.write(vcard.getBytes());
BufferedReader br = null;
String currentLine;
br = new BufferedReader(new FileReader("contact.vcf"));
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine);
}
fop.flush();
fop.close();
System.out.println("Kész");
} else
System.out.println("A fájl nem létezik");
}
You can use Scanner and do something like this
Scanner sc = new Scanner(System.in);
String input = sc.next();
See https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Or maybe you can pass what you need as parameters when running your application
See https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

How can i multiply all the numbers by 10 in java file I/O

Okay, so I have to Write a program to create a file named Lab13.txt. Write ten integers ranging [0, 99] created randomly into the file using text I/O. Integers are separated by spaces in the file. Read the data back from the file and display them on the console.
I've done this part already, but next I have to take those numbers in that file, create a new file, multiply all the numbers in the Lab13.txt file, and store them in the new file. My problem is when i create the new file, I'm only able to get it to multiply the last number printed from the Lab13.txt file. How do i get it to multiply all the numbers in Lab13.txt file by 10 and print them? This is probably a really simple solution and I feel so dumb for not being able to figure it out. Creating files is the new thing we're learning and my teacher is little to no help. :(
import java.io.*;
public class Lab13 {
public static void main(String ar[]) {
String toWrite = "";
int x=0;
try {
File file=new File("Lab13.txt");
FileWriter filewriter=new FileWriter(file);
BufferedWriter writer=new BufferedWriter(filewriter);
for(int i=0;i<10;i++) {
x=(int)(Math.random()*100);
writer.write(" "+x);
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
try {
File file1=new File("Lab13.txt");
FileReader filereader=new FileReader(file1);
BufferedReader reader=new BufferedReader(filereader);
String y;
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
File output = new File("lab13_scale.txt");
if(!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter= new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
You're never reading individual numbers from that line. And the x you multiplied with 10 was the last number you randomly generated in previous loop. That's why the problem.
Remove line -
toWrite += ("" + x*10);
Replace with -
String numArray = y.split(" ");
for (int i=0; i<numArray.length; i++) {
int newNum = Integer.parseInt(numArray[i]) * 10;
toWrite += ("" + newNum);
}
Your problem is here:
while((y=reader.readLine())!=null) {
System.out.println(y);
toWrite += ("" + x*10);
System.out.println(toWrite);
}
What reader.readLine() tells the reader to do is look for every newline character "\n" and process the chunks of text in between, and since you didnt add any, it treats the whole file as a single chunk.
What you can do instead is read the entire contents of the file into a string and then split it with the space delimiter (below is untested code):
String s = reader.readLine();
String[] allNumbers = s.split(" ");
for(String number : allNumbers) {
int currentNumber = Integer.parseInt(number);
bWriter.write(String.valueOf(currentNumber * 10) + " ");
}
public void multiply() throws Exception{
//reading from existing file
BufferedReader br = new BufferedReader(new FileReader("Lab13.txt"));
String l = br.readLine(); //assuming from your code that there is only one line
br.flush();
br.close();
String[] arr = l.split(" ");
//writing into new_file.txt
BufferedWriter bw = new BufferedWriter(new FileWriter("new_file.txt"));
for(String a : arr){
bw.write((Integer.parseInt(a)*10) + " ");
}
bw.flush();
bw.close();
}
Just call this method. Should work. You basically need to split the String using space. once that done, parsing each String into Integer and multiplying. and again storing.
package com.test;
import java.io.*;
public class Lab13
{
public static void main(String ar[])
{
String toWrite = "";
int x = 0;
try
{
File file = new File("Lab13.txt");
FileWriter filewriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(filewriter);
for (int i = 0; i < 10; i++)
{
x = (int) (Math.random() * 100);
writer.write(" " + x);
}
writer.close();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
File file1 = new File("Lab13.txt");
FileReader filereader = new FileReader(file1);
BufferedReader reader = new BufferedReader(filereader);
String y;
while ((y = reader.readLine()) != null)
{
////////////////////////////////////////
//trim - delete leading spaces from y
String[] array = y.trim().split(" ");
for (int i = 0; i < array.length; i++)
{
int number = Integer.parseInt(array[i]);
System.out.println(number);
toWrite += (number * 10 + " ");
}
System.out.println(toWrite);
////////////////////////////////////////
}
File output = new File("lab13_scale.txt");
if (!output.exists()) output.createNewFile();
FileWriter writer = new FileWriter(output.getAbsoluteFile());
BufferedWriter bWriter = new BufferedWriter(writer);
bWriter.write(toWrite);
bWriter.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}

program that uses input file and creates a new one

I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.

Checking if a file exists in java

So the following program should take in an input and output file as command line arguments.
class FileCopy
{
public static void main(String[] args) throws IOException
{
String infile = null;
String outfile = null;
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
if (args.length >= 2) //both files given via command line
{
infile = args[0];
if (fileExists(infile) == false)
{
infile = getInputFile();
}
outfile = args[1];
}
else if (args.length == 1) //input file given via command line
{
infile = args[0];
outfile = getOutputFile(infile);
}
else //no files given on command line
{
infile = getInputFile();
outfile = getOutputFile(infile);
}
//create file objects to use
File in = new File(infile);
File out = new File(outfile);
/*
*rest of code
*/
}
//get the input file from the user if given file does not exist
public static String getInputFile() //throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
boolean haveFile = false;
while(haveFile == false)
{
System.out.println("Enter a valid filename for input:");
System.out.print(">> ");
try
{
fileName = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
haveFile = fileExists(fileName);
}
return fileName;
}
//get the output file and test things
public static String getOutputFile(String infile)
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
File input = new File(infile);
String filename = null;
boolean more = true;
while(more)
{
System.out.println("Enter a valid filename for output:");
System.out.print(">> ");
try
{
filename = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
File output = new File(filename);
if (output.exists())
{
more = false;
}
if (filename == infile)
{
int selection;
String inputString = null;
System.out.println("The output file given matches the input file. Please choose an option:");
System.out.println("1) Enter new filename");
System.out.println("2) Overwrite existing file");
System.out.println("3) Backup existing file");
System.out.print(">> ");
try
{
inputString = stdin.readLine();
}
catch (IOException e)
{
System.out.println("Caught exception: " + e);
}
selection = Integer.valueOf(inputString);
switch (selection)
{
case 1: //new filename
case 2: //overwrite
case 3: //backup
default: System.exit(0);
}
}
}
return null;
}
//check the given file to see if it exists in the current working directory
public static boolean fileExists(String n)
{
return (new File(n)).exists();
}
}
One detail that I believe you have missed:
When your program has only one argument (args.length == 1), i.e. when only the input file is defined, fileExists() is not called at all; infile is set to args[0] with no validation at all. You should probably add a specific check as you have done for the two-argument case.
I've ran into a similar problem too. I was working under eclipse, and had to specify "src/file.txt" with my current directory having a file named "file" in the src directory.
Note: It was not named "file.txt" (this causes the string to be interpreted as "file.txt.txt"!).
Try testing against this program here assuming you have a file named "file" in your "src" directory:
import java.io.File;
public class FileChecker {
public static boolean Exists( String file )
{
System.out.println("File being checked: " + file);
return( (file.length()) > 0 && (new File(file).exists()) );
}
public static void main( String[] args )
{
File dir = new File("src");
System.out.println("List of files in source directory: ");
if( dir.isDirectory()){
File[] filenames = dir.listFiles();
for( Object file : filenames ) {
System.out.println(file.toString());
}
}
else
System.out.println("Directory does not exist.");
if(FileChecker.Exists("src/file.txt"))
System.out.println("File exists");
else
System.out.println("File does not exist");
}
}
It will print out the current files in source directory so you can see whether the file is really there or not, then you can test if it actually exists. Works on my end.

Count the amount of times a string appears in a file

I'm trying to figure out how I would read a file, and then count the amount of times a certain string appears.
This is what my file looks like, it's a .txt:
Test
Test
Test
Test
I want the method to then return how many times it is in the file. Any idea's on how I could go about doing this? I mainly need help with the first part. So if I was searching for the string "Test" I would want it to return 4.
Thanks in advanced! Hope I gave enough info!
Add this method to your class, pass your FileInputStream to it, and it should return the number of words in a file. Keep in mind, this is case sensitive.
public int countWord(String word, FileInputStream fis) {
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String readLine = "";
int count = 0;
while((readLine = in.readLine()) != null) {
String words = readLine.split(" ");
for(String s : words) {
if(s.equals(word)) count++;
}
return count;
}
Just wrote that now, and it's untested, so let me know if it works. Also, make sure that you understand what I did if this is a homework question.
Here you are:
public int countStringInFile(String stringToLookFor, String fileName){
int count = 0;
try{
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
int startIndex = strLine.indexOf(stringToLookFor);
while (startIndex != -1) {
count++;
startIndex = base.indexOf(stringToLookFor,
startIndex +stringToLookFor.length());
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return count;
}
Usage: int count = countStringInFile("SomeWordToLookFor", "FileName");
If you have got to the point of reading in each file into a string I would suggest looking at the String method split.
Give it the string code 'Test' and it will return an array of type string - count the number of elements per line. Sum them up to get your total occurrence.
import java.io.*;
public class StringCount {
public static void main(String args[]) throws Exception{
String testString = "Test";
String filePath = "Test.txt";
String strLine;
int numRead=0;
try {
FileInputStream fstream = new FileInputStream(filePath);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
strLine = strLine + " ";
String [] strArry = strLine.split(testString);
if (strArry.length > 1) {
numRead = numRead + strArry.length - 1;
}
else {
if (strLine == testString) {
numRead++;
}
}
}
in.close();
System.out.println(testString + " was found " + numRead + " times.");
}catch (Exception e){
}
}
}
I would do this:
open and read the file line by line,
check how oft a line contains the given word...
increase a global counter for that..
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("Test.txt"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter the subtring to look for: ");
String word = sc.next();
String line = in.readLine();
int count = 0;
do {
count += (line.length() - line.replace(word, "").length()) / word.length();
line = in.readLine();
} while (line != null);
System.out.print("There are " + count + " occurrences of " + word + " in ");
}

Categories

Resources