How to read characters in from a file from right to left - java

I am working on a program that evaluates lisp expressions using a stack implemented by either an array or linked list. I need to read the file in from the first line from right to left. Currently I am reading it in from left to right but I do not understand how I can switch it around. Any help you can give me is greatly appreciated! Thank you!
**I know the program is nowhere near complete, I just need to accomplish this before I can continue.
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
public class A2Q5{
private static Scanner in;
public static void main (String [] args)
{
if(args.length != 2) {
System.out.println("Please execute as: java A2Q5 type infile");
}
BoundedStack<Double> stack;
if(args[0].equals("0"))
stack = new BSArray<Double>(20);
else
stack = new BSLinkedList<Double>();
// The name of the file to open.
String fileName = args[1];
// This will reference one line at a time
//char c = null;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
for (int i = line.length() - 1; i >= 0; i--){
line.charAt(i);
System.out.println(line.charAt(i));
}
}
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file " + fileName);
}
catch(IOException ex) {
System.out.println("Error reading file " + fileName);
}
}
}

Drop the use of FileInputStream and use BufferedReader that you already prepared but never use. Use its method readLine to read info from your file line by line. Once you got an individual line you can iterate through it character by character from the end of the String to its beginning. This is exactly what you want.

Related

Order in column a N number of number rows on a txt file with java

I was trying to make an assignment my teacher gave and I have to order in column a set of number rows in a text file with Java
Disclaimer: my teacher doesn't want the Scanner class for this assigment: the sample data is this:
17,10,
6, 90,
11
The result should be this:
17
10
6
90
11
My code is this:
package esercizio.prova.verifica;
import java.io.*;
public class EsercizioProvaVerifica {
public static void main(String[] args) {
//read the file and put content in a String array
String[] str={};
String line = "";
try{
BufferedReader reader = new BufferedReader(new FileReader("C:\\sorgente\\file.txt"));
int i=0;
while((line=reader.readLine())!=null || i<str.length){
line = reader.readLine();
System.out.println(line + i);
str[i]=line;
i++;
}
reader.close();
} catch(IOException e){}
// Write array on file
for (int i=0;i<str.length;i++){
System.out.println(str[i]);
}
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\sorgente\\file.txt"));
for (int i = 0; i < str.length; i++) {
bw.write(str[i] + "\n"+ "");
}
bw.close();
}catch (IOException e1){}}}
The problem is everytime I run the program, the text in the file disappears and Java returns the following output:
run:
6, 90,0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at esercizio.prova.verifica.EsercizioProvaVerifica.main(EsercizioProvaVerifica.java:16)
C:\Users\franc\AppData\Local\NetBeans\Cache\8.2rc\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I searched for hours and I can't find the problem, Can someone help? Thanks a lot.
You initialize an empty array of length zero. The array length must be determined beforehand and cannot be changed during runtime. But since you don't know how many lines your file can have, arrays are not the right data structure. use a list instead.
Use try with resource. so you don't have to close your reader and writer manually.
While writing back you do not split the single numbers. Split each line at the commas.
Use the system line separator instead of \n so that your code behaves the same on all operating systems.
Don’t ignore exceptions, i.e don't do catch(IOException e){}
Example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("C:\\sorgente\\file.txt"))){
// read line by line and add to list
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\sorgente\\file.txt"))){
for(int i = 0; i < lines.size(); i++){
//splite each line at the commas
String[] parts = lines.get(i).split(",");
for(int k = 0; k < parts.length; k++){
//remove unnecessary spaces befor ore after comma using trim method
bw.write(parts[k].trim());
bw.write(System.lineSeparator());
}
}
}
catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
}
You have several problems.
You try to write to an array with no allocation.
You read within the while directive as well as within the while block. This causes you to skip values.
You're not splitting the values on their delimiter (,)
You're ignoring exceptions.
Here is one way to do it. There are quite a few. This uses a single loop to do both reading and wrting.
Open up the source file and create a temporary output file.
As you read in the line
split on the remaining ,s and write out the values.
when finished, close each file and then delete the original and then rename to the original.
try {
File input = new File("C:\\sorgente\\file.txt");
File output = File.createTempFile("temp",".txt");
BufferedReader reader = new BufferedReader(new FileReader(input));
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
String line = "";
while ((line = reader.readLine()) != null) {
for(String s : line.split(",")) {
writer.append(s.trim());
writer.newLine();
}
}
reader.close();
writer.close();
input.delete();
output.renameTo(input);
} catch (Exception e) {
e.printStackTrace();
}

How to write two texts files data into third file line by line in Java?

I read two files from different paths and while reading unable to write second file contents inside while loop, it is forcing me to initialize the variable which rt in below program. Please help me how to fix it to get
expected output. Thanks in advance..!!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReadingFiles
{
public static void main(String[] args) throws IOException
{
String inp = "location\\first.txt";
String two = "location\\second.txt";
BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
String st,rt;
BufferedWriter bw = new BufferedWriter(new FileWriter("location"));
while((st=br.readLine())!= null || (rt=br2.readLine())!= null )
{
bw.write(st);
bw.newLine();
/*bw.write(rt);
bw.newLine();
System.out.println(rt);*/
//instance variable rt of type String is forcing me to initialize like
//for local variable and throwing nullpointer exception instead of fetching
//second file contents
}
bw.close();
}
}
Please find my program above, i am trying to write two text files contents
into third file. And the sample input and output given below
input
in file-1 a1a1a1
b2b2b2
c3c3c3
in file-2 d1d1d1
e2e2e2
f3f3f3
output
a1a1a1
d1d1d1
b2b2b2
e2e2e2
c3c3c3
f3f3f3
There is several mistakes you have done in the code and also there are better ways to implement the code.
But for your understatement i will update your existing code.
1) st and rt should be initialized. because when first time st is initializing rt is not yet initialized.
2) || should be &&. because you need to loop until all the files are finished reading.
3) st & rt should be checked if it's null or not.
please check following code .
public class ReadingFiles
{
public static void main(String[] args) throws IOException
{
String inp = "first.txt";
String two = "second.txt";
BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
String st,rt="";
BufferedWriter bw = new BufferedWriter(new FileWriter("location"));
boolean isCompleted = false;
while( !isCompleted)
{
st=br.readLine() ;
bw.write(st==null?"":st);
bw.newLine();
rt=br2.readLine();
bw.write(rt==null?"":rt);
bw.newLine();
isCompleted = (st==null && rt == null) ? true : false ;
}
bw.close();
}
}
I would do this with an infinite do while loop instead of while and manage the loop exit condition in a seperate if inside my loop.
Why? Because the second conditional statement in your while header may not be executed since it is an or (||) and the compiler ignores the rest of your conditional statement when the first statement istrue and therefore rtnever get initiated. Thats why the compiler is forcing you to initialize rt.
You aren't closing your readers, and I would prefer the try-with-resources over explicit closes. Then, read each line from your respective files in an infinite loop. Test for null from each file individually before writing to the output buffer, and again at the end to terminate your loop when you have exhausted both inputs. Something like,
try (BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
BufferedWriter bw = new BufferedWriter(new FileWriter("location"))) {
while (true) {
String st = br.readLine();
if (st != null) {
bw.write(st);
bw.newLine();
}
String rt = br2.readLine();
if (rt != null) {
bw.write(rt);
bw.newLine();
}
if (st == null && rt == null) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}

How do I assign values from a Textfile with BufferedReader from a specific line?

package inputOutput;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Test_leser {
public static void main(String[] args) throws IOException {
// asking which file to open (no abändre das es dynamisch übere Browser funktioniert)
Scanner scan = new Scanner(System.in);
System.out.println("Enter Filename ");
BufferedReader bReader = null;
// Open demanded file
try {
bReader = new BufferedReader(
new FileReader("C:\\Users\\valat\\OneDrive\\Desktop\\image-data\\" + scan.next()));
} catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage());
// Programm geht nicht weiter, falls file not found
System.exit(0);
}
String line;
String resolution = null;
String image = null;
String description = null;
int i = 0;
// assigning values to variables
while ((line = bReader.readLine()) != null) {
// zähler
i += 1;
if (line.startsWith("description:")) {
description = line;
}
else if (line.startsWith("image-file")) {
image = line;
}
else if (line.startsWith("resolution:")) {
resolution = line;
} else {
System.out.println("something is REALLY wrong");
}
System.out.println(description);
System.out.println(image);
System.out.println(resolution);
}
}
}
Hey. I'm having trouble here.
I'm reading this text with a BufferedReader from a textfile:
description: Blutausstrich (Mensch)
image-file: image01.jpg
resolution: 0.002 mm
after that my next intention is to iterate through each line, and assign each line on its own to a variable.
The problem is, my output, whenever I try it, is the following:
description: Blutausstrich (Mensch)
null
null
description: Blutausstrich (Mensch)
image-file: image01.jpg
null
description: Blutausstrich (Mensch)
image-file: image01.jpg
resolution: 0.002 mm
As you can probably see, that isn't exactly what I want. How can I assign just the specific lines which fullfill my if-condition from the txtfile with my variables? I would really appreciate some help, I'm trying to play aroung with this one for hours, I looked up so many different things, and I'm pretty sure it's a pretty obvious answer which will make me think "oh bloody hell, seriously? I'm a moron".
Thank you guys in advance!
Move stdout out of while loop:
System.out.println(description);
System.out.println(image);
System.out.println(resolution);
The problem is we are printing before assignment of all the variables.
Cheers !

Java Program to write text file, using separator, and in first line write record number [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to write in file, I need to write total number of the record in first line, and in while loop write all other line, everything working good but, in first line need to write total number of the record how can i do that, Please help me!! Thanks!!
Here is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class headerline {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File folderall = new File("FilesIn1");
File[] BFFileall = folderall.listFiles();
for (final File file : BFFileall) {
String str = file.getName();
BufferedReader br = null;
BufferedWriter lbwp = null;
BufferedWriter lb = null;
try {
int lbwpcount = 1;
int lbcount = 1;
String reprintbwletterbwpca = (str);
lbwp = new BufferedWriter(new FileWriter(reprintbwletterbwpca));
lbwp.write("Total line number: " + lbwpcount);
String reprintbwletterbwpcalb = (str);
lb = new BufferedWriter(new FileWriter(reprintbwletterbwpcalb));
lb.write("Total line number: " + lbwpcount);
br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] actionID = line.split("|");
String actionid = actionID[2];
String custnumber = actionID[3];
lbwp.write("ActionID: " + actionid + ",CustomerNumber: " + custnumber + "\r\n");
lbwpcount++;
lb.write("ActionID: " + actionid + ",CustomerNumber: " + custnumber + "\r\n");
lbcount++;
}
lbwp.close();
lb.close();
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
}
suppose file has 1201 lines, it should print
Total line number: 1200, in first line.
than
"ActionID: " + actionid + ",CustomerNumber: " + custnumber
..........
suppose other file has 1451 lines, it should print
Total line number: 1450, in first line.
than
"ActionID: " + actionid + ",CustomerNumber: " + custnumber
..........
I have no idea how can i do that, please help me!! can i write first line as last after finish while loop??
Thanks in advanced!!
Simply use java.nio.file package. It has class Files which has a method readAllLines(...). This will read all lines and add it to a List. Simply use List.size() to get number of lines, and write it to another file as you wanted :-)
Try this program, this will let you know the number of lines in the file :
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.List;
public class ReadAndWriteFile {
private Path actualPath;
private Path sourcePath;
private BufferedReader reader;
private BufferedWriter writer;
private List<String> lines;
public ReadAndWriteFile() {
sourcePath = Paths.get("xanadu.txt");
//sourcePath = sourcePath.toAbsolutePath();
actualPath = Paths.get("xanadu_new.txt");
//targetPath = actualPath.toAbsolutePath();
Charset charset = Charset.forName("US-ASCII");
try {
lines = Files.readAllLines(sourcePath, charset);
System.out.println("Number of Lines : " + lines.size());
reader = Files.newBufferedReader(sourcePath, charset);
writer = Files.newBufferedWriter(actualPath, charset);
String message = "Total Line Number : " + lines.size();
writer.write(String.format("%s%n", message));
for (String line : lines) {
System.out.println(line);
writer.write(String.format("%s%n", line));
}
reader.close();
writer.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
new ReadAndWriteFile();
}
}
Text File (xanadu.txt) Contents :
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Through caverns measureless to man
Down to a sunless sea.
You can use Apache Commons FileUtils.readLines(). This returns you all lines in your original file as a list, from which you can get the size.
Otherwise you would have to read all the lines manually to count them first and then write them to the file.
Here's a high level explanation:
Loop through all the lines and store it in a List<Record>.
Write the total number of elements in your List<Record> as the first line (this will be total number of records)
In a loop, write the record data to the rest of the file
Since you need the total first, that means you've gotta loop once to find out what the total is. Then loop again to write the records.
You cannot know the total line number until you have read all the lines of the file.
Some options available to you are:
Read the file twice. The first time, simply keep a count the number of lines. Print it. Then read the file a second time, and write our the records like you are doing at the moment.
Hold the records in memory temporarily. As you read the file, keep the content in a collection (e.g. ArrayList) and write it out at the end. You can use list.size() to get the number of records. You could use use Apache Commons FileUtils.readLines() to do this, if you don't mind introducing a JAR dependency. EDIT: Or write your own method (see below).
Prepend the record count afterwards. Write out the file then as you are doing then prepend the record count to the file.
Challenge the requirements. Ask if it is really necessary to output the record count at the start? Could it be omitted? Could it be at the end? Etc.
Here's some sample code for option 2 - a method for reading the file into a list that you can manipulate:
public static List<String> readLines(File file) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} finally {
br.close();
}
return lines;
}
You use it like this:
File file = new File("example.txt");
List<String> lines = readLines(file);
int lineCount = lines.size();
// TODO: Write out the line count
for (String line : lines) {
// TODO: Process the line
}

Java Read from file to Array runtime error

import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();

Categories

Resources