How to put read and cast into a char array - java

I have a source txt file and I am trying to read the characters using the .read() method of the FileReader class. I have got the integer values that come out the .read and cast them to char and looped the output to check this is working. The problem is that when I try to store them in an array, the array prints empty.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReversedQuotation {
public static void main(String[] args) {
char[] charArray = new char[1000];
char[] sortedQuote = new char[1000];
int counter = 999;
int secondCounter = 0;
FileReader fr = null;
try {
fr = new FileReader("/Users/cal/Desktop/backwards.txt");
while(true) {
try {
int charInt = fr.read();
if(charInt == -1) break;
charArray[counter] = (char)charInt;
counter--;
System.out.print(charArray[counter]);
System.out.print((char)charInt); // just to check the characters are correct.
charArray[counter] = sortedQuote[secondCounter];
secondCounter++;
System.out.print(sortedQuote[secondCounter]);
}
catch (IOException e) {
System.out.println("IO Error in reading document");
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error finding document.");
} finally {
try {
fr.close();
} catch(IOException e) {
System.out.println("Error in closing the File Reader.");
}
}
}
}

First:
charArray[counter] = (char)charInt; // say counter = 999
counter--;
System.out.print(charArray[counter]); // charArray[998]
This will print the value at decremented index(which is essentially empty) and not the assigned index.
charArray[counter] = (char)charInt;
System.out.print(charArray[counter]);
counter--;
This should print what you have assigned.
Second:
sortedQuote[secondCounter] is never assigned and
charArray[counter] = sortedQuote[secondCounter] assignment seems to have no purpose.

Related

deleting a specific lines in txt file then copy to a new txt file

i am having some problem in java, i wanted to remove number 5 to number 7 and save them into a new file called RevisedNumbers.txt, is there any way to do that? this is my code so far
import java.util.Scanner;
import java.io.*;
public class Txt {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File myObj = new File("Numbers1to10.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
Writer writer = new PrintWriter("Numbers1to10.txt");
for(int i = 1; i <= 10; i++)
{
writer.write("Number" + i);
writer.write("\r\n");
}
writer.close();
File readFile = new File("Numbers1to10.txt");
Scanner read = new Scanner(readFile);
while (read.hasNextLine())
System.out.println(read.nextLine());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
File myObj = new File("RevisedNumbers.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
the desired output on the new file will be
Number 1
Number 2
Number 3
Number 4
Number 8
Number 9
Number 10
One possible solution might be using an additional file.
While reading the contents of the first file ("Numbers1to10.txt"), if values are within 5 to 7, then write it into the second file ("RevisedNumbers.txt"), otherwise write it into the additional file.
Now the additional file contains values that you need in the first file. So copy all contents of the additional file into the first file.
Here is a sample code.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWriteMain {
static void _write1to10(String locationWithFileName) {
try {
File file = new File(locationWithFileName);
boolean fileAlreadyExist = file.exists();
if (fileAlreadyExist) {
System.out.println("File already exists!");
} else {
System.out.println("New file has been created.");
}
FileWriter fileWriter = new FileWriter(file);
for (int i = 1; i <= 10; i++) {
fileWriter.write("Number " + i);
fileWriter.append('\n');
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static File _getFile(String locationWithFileName) {
File file = null;
file = new File(locationWithFileName);
return file;
}
// it reads a file and print it's content in console
static void _readFile(Scanner scanner) {
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
System.out.println(currLine);
}
}
// read contents from sourceFile file and copy it into destinationFile
static void _copyFromOneFileToAnother(File sourceFile, File destinationFile) throws IOException {
FileWriter destFileWriter = new FileWriter(destinationFile);
Scanner scanner = new Scanner(sourceFile);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
destFileWriter.write(currLine);
destFileWriter.append('\n');
}
destFileWriter.close();
}
public static void main(String[] args) {
String locationWithFileName = "E:\\FileWriteDemo\\src\\Numbers1to10.txt"; // give your file name including it's location
_write1to10(locationWithFileName);
System.out.println("File writing done!");
File file1 = _getFile(locationWithFileName);
try {
// creating file 2
String locationWithFileName2 = "E:\\FileWriteDemo\\src\\RevisedNumbers.txt";
File file2 = _getFile(locationWithFileName2);
FileWriter fileWriter2 = new FileWriter(file2);
// creating a temporary file
String tempFileLocationWithName = "E:\\FileWriteDemo\\src\\temporary.txt";
File tempFile = _getFile(tempFileLocationWithName);
FileWriter tempFileWriter = new FileWriter(tempFile);
Scanner scanner = new Scanner(file1);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
// split the word "Number" from integer
String words[] = currLine.split(" ");
for (int i = 0; i < words.length; i++) {
// System.out.println(words[i]);
try {
int num = Integer.parseInt(words[i]);
if (num >= 5 && num <= 7) {
// writing to second file
fileWriter2.write(currLine);
fileWriter2.append('\n');
} else {
// writing to temporary file
tempFileWriter.write(currLine);
tempFileWriter.append('\n');
}
} catch (NumberFormatException e) {
// current word is not an integer, so don't have to do anything
}
}
}
fileWriter2.close();
tempFileWriter.close();
_copyFromOneFileToAnother(tempFile, file1);
System.out.println("\nContents of first file");
_readFile(new Scanner(file1));
System.out.println("\nContents of second file");
_readFile(new Scanner(file2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope it helps!
Happy coding.

Why I could not save the contents of a file after reading it twice?

Already fixed. Thanks for Mas & ruhul for observing my bugs.
I was trying to read a text file twice, named stationary.txt. The contents of the file has three columns such as the amount, the name of product and the total price.
What I am trying to do first is by averaging each product's price by reading line by line. Then I closed the Buffered and then open it again and read. The second reading takes a variable average and compares each product's price line by line. If line 1 is over the average, then write it into dearer.txt, otherwise write it into cheap.txt
Here is the stationary.txt
1 Highlighter 5.99
2 Pen 9.00
3 Eraser 5.00
4 DrawingPin 2.75
5 Highlighter 10.99
6 FountainPen 20.50
7 Pencil 14.50
Below is the source code
import java.util.*;
import java.io.*;
public class Ques {
public static void main(String[] args) throws FileNotFoundException {
double average = 0;
File inFile = new File("stationary.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
File outFilel = new File("dearer.txt");
FileOutputStream outFileStreaml = new FileOutputStream(outFilel);
PrintWriter outStream1 = new PrintWriter(outFileStreaml);
File outFile2 = new File("cheap.txt");
FileOutputStream outFileStream2 = new FileOutputStream(outFile2);
PrintWriter outStream2 = new PrintWriter(outFileStream2);
computeAverage(bufReader, outStream1, outStream2, average);
}
public static void computeAverage(BufferedReader bufReader, PrintWriter outStream1, PrintWriter outStream2, double average) {
String line = "";
double mark = 0;
double sum = 0;
int count = 0;
try {
bufReader.readLine();
while ((line = bufReader.readLine()) != null) {
String [] data = line.split(" ");
mark = Double.parseDouble(data[2]);
sum += mark;
count++;
}
average = sum / count;
compareMark(outStream1, outStream2, average);
} catch (NumberFormatException | IOException e) {
System.out.println(e);
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
public static void compareMark(PrintWriter outStream1, PrintWriter outStream2, double average) throws FileNotFoundException {
File inFile = new File("stationary.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
String line = " ";
double sum = 0;
double mark = 0;
int count = 0;
try {
double ave = (double) Math.round(average * 100) / 100;
System.out.println("another " + ave);
bufReader.readLine();
while ((line = bufReader.readLine()) != null) {
System.out.println(line);
String [] data = line.split(" ");
mark = Double.parseDouble(data[2]);
if (mark > ave) {
System.out.println("Over");
outStream1.write(line);
} else {
System.out.println("Less");
outStream2.write(line);
}
}
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException ex) {
System.out.println(ex);
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The source code is perfectly working, just that I received 0 bytes of both files after executing reading twice (first, doing average and last, doing comparison). Why is that? what am I doing wrong here?
Thank you for your kind help.
Your code is not correct and does not compile. But the main flaws are the following:
Your Double.parseDouble(data[2]) shouldn't work with your 4th line of data. Better use Double.parseDouble(data[data.length - 1])
Remove the readLine()-calls in front of the while-loop.
Write the lines including a line separator.
Close the OutStreams
The Data File that you have provided have the columns seperated by a space. As the 2nd Column has data which contains spaces, the convertion of data[2] to double will trigger an exception. Which will make the program to close the buffers and exit.
Use Commas to seperate column data.
Use better exception handling to find exceptions easily.
All you need is to close those output stream. As you are using bufferredWriter and not flushing it after each write you need to close those output-stream. which will write back those lines or datas into the file. Here is an example how you can do it:
Example 1: using flush().
....
outStream1.write(line);
outStream1.flush();
} else {
System.out.println("Less");
outStream2.write(line);
outStream2.flush();
}
Example 2: most efficient (either way you need to close those buffer too like bufReader.close())
...
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException ex) {
System.out.println(ex);
} finally {
// add try catch.
outStream2.close();
outStream1.close();
if (bufReader != null ... ) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As requested, an example using List
First a class to hold the stationary data, must be completed:
public class Stationary {
private final int id; // or String if desired
private final String name;
private final double mark; // BigDecimal would be better for money
public Stationary(int id, String name, double mark) {
// TODO error checking
this.id = id;
...
}
public int getId() {
return id;
}
... // TODO other getters
// TODO equals, hashCode, toString
}
and to read the file:
public List<Stationary> read(File file) {
List<Stationary> list= new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
// TODO parse line into id, name, mark
list.add(new Stationary(id, name, mark);
}
}
return list;
}
now the list can be used as needed, e.g. average:
List<Stationary> stationaries = read(STATIONARY_FILE);
...
for (Stationary stationary : stationaries) {
sum += stationary.getMark();
count += 1;
}
...
streams not used to keep it simple

Why is there no output when I run my code?

I am trying to read a file called ecoli.txt, which contains the DNA sequence for ecoli, and store its contents into a string. I tried to print the string to test my code. However, when I run the program, there is no output. I am still new to java so I am sure there is an error in my code, I just need help finding it.
package codons;
import java.io.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader codons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_string = new StringBuilder();
String line = ecoli.readLine();
while(line != null);
{
dna_string.append(line);
line = ecoli.readLine();
}
String string = new String(dna_string);
System.out.println(string);
ecoli.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
edit:
I was still having trouble getting the program to work the way I wanted it to so I attempted to complete writing the rest of what I wanted in the program and I am still not getting any output. Anyway, this is where I am at now:
package codons;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader filecodons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_sb = new StringBuilder();
String line = ecoli.readLine();
while(line != null)
{
dna_sb.append(line);
line = ecoli.readLine();
}
String dna_string = new String(dna_sb);
ecoli.close();
BufferedReader codons = new BufferedReader(filecodons);
StringBuilder codon_sb = new StringBuilder();
String codon = codons.readLine();
while(codon != null)
{
codon_sb.append(codon);
line = codons.readLine();
}
String codon_string = new String(codon_sb);
codons.close();
for(int x = 0; x <= codon_sb.length(); x++)
{
int count = 0;
String codon_ss = new String(codon_string.substring(x, x+3));
for(int i = 0; i <= dna_sb.length(); i++)
{
String dna_ss = new String(dna_string.substring(i, i+3));
int result = codon_ss.compareTo(dna_ss);
if(result == 0)
{
count += 1;
}
}
System.out.print("The codon '");
System.out.print(codon_ss);
System.out.print("'is in the dna sequence");
System.out.print(count);
System.out.println("times.");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Remove the ; after while(line != null), it causes an infinite loop instead of executing the next instructions.
The reason is explained here: Effect of semicolon after 'for' loop (the question is about the C language, but it is equivalent in Java).

Issue with using an array to store/print files from Linux

I cant figure out how to loop through this instead of just repeating the code, bugging the hell outta me! FYI assignment has already been turned in using 5 iterations of code, just wanted to learn how to implement the string array holding file contents into a for loop for future knowledge. I have tried for a few hours but it just prints the filename, cant seem to get the file contents.
/*************************************************************************
* LinuxSys.java
*
* This program reads text from a file
**************************************************************************/
import java.util.*;
import java.io.*;
public class LinuxSys {
public static void main (String[] args) {
String systemInfo[] = new String [5];
int i = 0;
// using _ to simulate file paths to test on local cpu, as it is easier/quicker
// than logging onto server/copy pasting code into new pico file
systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
systemInfo[1] = "_proc_meminfo.txt"; //local files
systemInfo[2] = "_proc_version.txt"; //local files
systemInfo[3] = "_proc_sys_kernel_hostname.txt"; //local files
//systemInfo[0] = "_proc_sys_kernel_hostname.txt"; //local files
// 1st try to print server host name file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 2nd try to print server memory file
{
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++; // increment systemInfo[] array position
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
// 3rd try to print version file
try {
BufferedReader inputStream =
new BufferedReader(new FileReader(systemInfo[i]));
String line = "blank";
while (line != null) {
if((line = inputStream.readLine()) != null) {
System.out.println(line);
i++;
} // end if
} //end while
System.out.println(); // create space
inputStream.close();
} // end try
catch(FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened");
} //end catch
catch(IOException e) {
System.out.println("Error reading from file");
} //end catch
} // end main
} // end class
for(int i=0; i < systemInfo.size; ++i)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
while(i < systemInfo.size)
{
// the code you want to repeat with i varying each time
++i;
}
or
int i=0;
while(i++ < systemInfo.size)
{
// the code you want to repeat with i varying each time
}
or
int i=0;
do
{
// the code you want to repeat with i varying each time
}
while(++i < systemInfo.size)
or...

How to read a file, reverse the order, and write reverse order

Like a similar project I made, this project is reading characters from a txt file, reversing the order of the string and rewriting it to another txt file. But it keeps outputting my exception of "Something went wrong". Can anyone help me fix what is going wrong?
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReverseFile
{
public static void main(String[] args) throws IOException
{
try{
String source = args[0];
String target = args[1];
File sourceFile=new File(source);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(target);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
System.out.println("File is copied successful!");
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
So here is the information from the stacktrace:
java.lang.ArrayIndexOutOfBoundsException: 0
at ReverseFile.main(ReverseFile.java:36)
i am not so sure about your environment, and how long the text might be. and i am also not so sure why you need a scanner?
anyway, here's my take on the problem, hope this helps you :)
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
public class Reverse {
public static void main(String[] args) {
FileInputStream fis = null;
RandomAccessFile raf = null;
// by default, let's use utf-8
String characterEncoding = "utf-8";
// but if you pass an optional 3rd parameter, we use that
if(args.length==3) {
characterEncoding = args[2];
}
try{
// input file
File in = new File(args[0]);
fis = new FileInputStream(in);
// a reader, because it respects character encoding etc
Reader r = new InputStreamReader(fis,characterEncoding);
// an outputfile
File out = new File(args[1]);
// and a random access file of the same size as the input, so we can write in reverse order
raf = new RandomAccessFile(out, "rw");
raf.setLength(in.length());
// a buffer for the chars we want to read
char[] buff = new char[1];
// keep track of the current position (we're going backwards, so we start at the end)
long position = in.length();
// Reader.read will return -1 when it reached the end.
while((r.read(buff))>-1) {
// turn the character into bytes according to the character encoding
Character c = buff[0];
String s = c+"";
byte[] bBuff = s.getBytes(characterEncoding);
// go to the proper position in the random access file
position = position-bBuff.length;
raf.seek(position);
// write one or more bytes for the character
raf.write(bBuff);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// clean up
try {
fis.close();
} catch (Exception e2) {
}
try {
raf.close();
} catch (Exception e2) {
}
}
}
}
You need to specify the filenames(source and target) on command-line, while running the program.
java ReverseFile source.txt target.txt
In your program, you try to read the name of files from command-line as
String source = args[0];
String target = args[1];
So if you do not specify those names there, java tries to access the array args at index 0 and 1 which are empty and you get ArrayIndexOutOfBoundsException.
here is ur error free solution to ur problem,u were using "Scanner" without importing "util"
package.here we go:-----------
import java.io.*;
import java.util.*;
public class ReverseFile
{
public static void main(String[] args) throws IOException
{
try{
File sourceFile=new File(args[0]);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(args[1]);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
System.out.println("File is copied successful!");
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
Just thought of a simple approach.
public class ReadFileReverse {
public int[] readByte(File _file) throws IOException {
FileInputStream source = new FileInputStream(_file);
int currentByte = source.available();
int readCount = 0;
int byteContainer[] = new int[currentByte];
while(readCount < currentByte){
byteContainer[readCount] = source.read();
readCount++;
}
source.close();
return byteContainer;
}
public void printReverse(int[] fileContent){
for(int byt=fileContent.length -1; byt >= 0 ; byt--){
System.out.print((char) fileContent[byt]);
}
}
public static void main(String[] args) throws IOException {
File fileToRead = new File("/README.txt");
ReadFileReverse demo = new ReadFileReverse ();
int[] readBytes = demo.readByte(fileToRead);
demo.printReverse(readBytes);
}
}
Here we are reading a file in string variable, then making a String Builder object to perform reverse operation efficiently, then printing
package com;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("D:\\newfile.txt");
String str = "";
int ch;
//reading characters in to string variable
while ((ch = fr.read()) != -1) {
str += Character.toString((char) ch);
}
System.out.println("Original String : " + str);
//converting string variable to String Builder object
StringBuilder sb = new StringBuilder(str);
//reversing the string and printing
System.out.println("Reverse order : " + sb.reverse());
fr.close();
} catch (Exception e) {
System.out.println("error");
}
}
}
Output:

Categories