My goal for this program is to read a text file, print it normally, then print it flipped from left to right, and then flipped upside down. I can print the original, however I'm unsure of how to read the file so it will print in the other two formats, and how to print in these formats. I can only import the file once.
Here is an example output, if my description is inadequate.
The code as it is now:
import java.io.*;
import java.util.*;
public class Problem2
{
public static void main(String[] args) throws IOException
{
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext())
{
original = fileScan.nextLine();
System.out.println(original);
}
String lefttoright;
while (fileScan.hasNext())
{
lefttoright = fileScan.nextLine();
System.out.println(lefttoright);
}
String upsidedown;
while (fileScan.hasNext())
{
upsidedown = fileScan.nextLine();
System.out.println(upsidedown);
}
fileScan.close();
}
}
Try to use StringBuilder(element).reverse().toString(); where element is a string.
Example of working code:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\xxx\\Documents\\test.txt");
List<String> listString = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
//write as is
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
//write in reverse
while ((line = br.readLine()) != null) {
String result = new StringBuilder(line).reverse().toString();
System.out.println(result);
}
System.out.println("");
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
listString.add(line);
}
//write down up
Collections.reverse(listString);
for (String element : listString) {
String result = new StringBuilder(element).reverse().toString();
System.out.println(result);
}
}
}
Test example:
test.txt file content:
alpha
tree
123
Output:
alpha
tree
123
ahpla
eert
321
321
eert
ahpla
You might consider as below. this will save you the hassle with reading 3 times from the file.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
System.out.println(original);
System.out.println();
System.out.print(flip(original));
System.out.println();
System.out.print(updsideDown(original));
}
public static String flip(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = 0; i < intermInput.length; i++) {
StringBuffer strBuff = new StringBuffer(intermInput[i]);
output.append(strBuff.reverse());
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
public static String updsideDown(String input) {
StringBuffer output = new StringBuffer();
String[] intermInput = input.split("\n");
for (int i = intermInput.length - 1; i >= 0; i--) {
output.append(intermInput[i]);
output.append("\n");
}
output.substring(0, output.length());
return output.toString();
}
}
Either use suggestion from YCF_L or use below solution.
import java.io.*;
import java.util.*;
public class Problem2 {
public static void main(String[] args) throws IOException {
File marge = new File("marge.txt");
Scanner fileScan = new Scanner(marge);
String original;
while (fileScan.hasNext()) {
original = fileScan.nextLine();
System.out.println(original);
}
fileScan = new Scanner(marge);
String lefttoright;
while (fileScan.hasNext()) {
lefttoright = fileScan.nextLine();
StringBuffer sb = new StringBuffer(lefttoright);
System.out.println(sb.reverse());
}
fileScan = new Scanner(marge);
String upsidedown;
Stack<String> list = new Stack<String>();
while (fileScan.hasNext()) {
upsidedown = fileScan.nextLine();
list.push(upsidedown);
}
for (int i = 0; i <= list.size(); i++) {
System.out.println(list.pop());
}
fileScan.close();
}
}
Related
I have two text files. I have to develop a java program which compares the two files and find unique words. I have tried a few methods but didn’t work. Example:
test1.txt:
I am a robot. My name is Sofia.
test2.txt:
Hello I am a man. My name is Alex
Output:
Hello robot man Sofia Alex
I approach was like this:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("test1.txt"));
Scanner scan = new Scanner(new File("test2.txt"));
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> a2 = new ArrayList<String>();
String test;
while (input.hasNext()) {
String next = input.next();
}
System.out.println("arraylist" + al);
while (scan.hasNext()) {
test = scan.next();
a2.add(test);
}
System.out.println("arraylist2" + a2);
for( int i = 0; i < al.size(); i++){
for(int j = 0; j < a2.size(); j++){
if(al.get(i).equals(a2.get(j))){
break;}
else{
System.out.println(al.get(i));break;
}
}
}
}
}
Note that this is a quick and dirty approach and pretty inefficient. Furthermore I dont know your exact requirements (full stops? Upper/lowercase?).
Also take into account that this program doesn't check which list is longer. But this should give you a good hint:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("test1.txt"));
Scanner scan = new Scanner(new File("test2.txt"));
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
while (input.hasNext()) {
list1.add(input.next());
}
while (scan.hasNext()) {
list2.add(scan.next());
}
// iterate over list 1
for (int i = list1.size() - 1; i >= 0; i--) {
// if there is a occurence of two identical strings
if (list2.contains(list1.get(i))) {
// remove the String from list 2
list2.remove(list2.indexOf(list1.get(i)));
// remove the String from list 1
list1.remove(i);
}
}
// merge the lists
list1.addAll(list2);
// remove full stops
for (int i = 0; i < list1.size(); i++) {
list1.set(i, list1.get(i).replace(".", ""));
}
System.out.println("Unique Values: " + list1);
}
}
Assumptions are the text file contains only (.) as sentence terminator.
public static void main(String[] args) throws Exception
{
// Skipping reading from file and storing in string
String stringFromFileOne = "I am a robot. My name is Sofia.";
String stringFromFileTwo = "Hello I am a man. My name is Alex";
Set<String> set1 = Arrays.asList(stringFromFileOne.split(" "))
.stream()
.map(s -> s.toLowerCase())
.map(m -> m.contains(".") ? m.replace(".", "") : m)
.sorted()
.collect(Collectors.toSet());
Set<String> set2 = Arrays.asList(stringFromFileTwo.split(" "))
.stream()
.map(s -> s.toLowerCase())
.map(m -> m.contains(".") ? m.replace(".", "") : m)
.sorted()
.collect(Collectors.toSet());
List<String> uniqueWords;
if (set1.size() > set2.size()) {
uniqueWords = getUniqueWords(set2, set1);
} else {
uniqueWords = getUniqueWords(set1, set2);
}
System.out.println("uniqueWords:" + uniqueWords);
}
private static List<String> getUniqueWords(Set<String> removeFromSet, Set<String> iterateOverSet) {
List<String> uniqueWords;
Set<String> tempSet = new HashSet<String>(removeFromSet);
removeFromSet.removeAll(iterateOverSet);
uniqueWords = iterateOverSet.stream().filter(f -> !tempSet.contains(f) && !f.isEmpty())
.collect(Collectors.toList());
uniqueWords.addAll(removeFromSet);
return uniqueWords;
}
You can use guava library which gives you difference between two sets.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import com.google.common.collect.Sets;
public class WordTest {
public static void main(String[] args) {
WordTest wordTest = new WordTest();
Set<String> firstFileWords = wordTest.getAllWords("E:\\testing1.txt");
Set<String> secondFileWords = wordTest.getAllWords("E:\\testing2.txt");
Set<String> diff = Sets.difference(firstFileWords, secondFileWords);
Set<String> diff2 = Sets.difference(secondFileWords, firstFileWords);
System.out.println("Set 1: " + firstFileWords);
System.out.println("Set 2: " + secondFileWords);
System.out.println("Difference between " + "Set 1 and Set 2: " + diff);
System.out.println("Difference between " + "Set 2 and Set 1: " + diff2);
}
public Set<String> getAllWords(String path) {
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Set<String> wordList = new HashSet<>();
try {
fis = new FileInputStream(path);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ,.;:\"");
while (st.hasMoreTokens()) {
wordList.add(st.nextToken());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
return wordList;
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
public class FileComparision {
public static void main(String[] args) throws IOException {
HashSet<String> uniqueSet=new HashSet<String>();
//split the lines based on the delimiter and add it to set
BufferedReader reader=new BufferedReader(new FileReader("test1.txt"));
String line;
while ((line = reader.readLine()) != null) {
Arrays.asList(line.split(" ")).forEach(word->uniqueSet.add(word) ); ;
}
reader.close();
reader=new BufferedReader(new FileReader("test2.txt"));
while ((line = reader.readLine()) != null) {
Arrays.asList(line.split(" ")).forEach(word->{
if(!uniqueSet.contains(word)) {
uniqueSet.add(word) ;
}else {
uniqueSet.remove(word);
}
});
}
reader.close();
//to remove unnecessary characters
//uniqueSet.remove(".");
System.out.println(uniqueSet);
}
}
public static String readFile(String fileName)throws Exception
{
String data = "";
data = new String(Files.readAllBytes(Paths.get(fileName)));
return data;
}
public static void main(String[] args) throws Exception
{
String data = readFileAsString("C:\\Users\\pb\\Desktop\\text1.txt");
String data1 = readFileAsString("C:\\Users\\pb\\Desktop\\text2.txt");
String array[]=data.split(" ");
String array1[]=data1.split(" ");
for(int i=0;i<=array1.length-1;i++){
if(data.contains(array1[i])){
}else{
System.out.println(array1[i]);
}
}
for(int i=0;i<=array.length-1;i++){
if(data1.contains(array[i])){
}else{
System.out.println(array[i]);
}
}
}
import java.io.*;
import java.util.*;
public class stringstore
{
public static void main(String[] args)
{
File file = new File("C:\\a.txt");
try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
String line = sc.nextLine();
String str[] = line.split(", ");
strIP = str[0];
}
System.out.println(strIP);
}
catch(IOException e)
{
// work with the errors here
}
}
}
How do I read a nextline from a textfile and display it.
There is only slight mistake in your code.
Try this.
import java.io.*;
import java.util.*;
public class stringstore
{
public static void main(String[] args)
{
File file = new File("C:\\a.txt");
try
{
String strIP="";
Scanner sc = new Scanner(file);
while(sc.hasNext())
{
String line = sc.nextLine();
String str[] = line.split(", ");
strIP = str[0];
System.out.println(strIP);
}
}
catch(IOException e)
{
// work with the errors here
}
}
}
place the print statement inside the loop
You can read file line by line:
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("filename")));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}
I have a text file with the following contents:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
I have an array num[]= {2,3,4}; which contains the line numbers to be completely replaced with the strings from this array
String[] VALUES = new String[] {"AB","BC","CD"};
That is line 2 will be replaced with AB, line 3 with BD and ine 4 with CD.
Lines which are not in the num[]array have to be written to a new file along with the changes made.
I have this so far.I tried several kind of loops but still it does not work.
public class ReadFileandReplace {
/**
* #param args
*/
public static void main(String[] args) {
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
int l = num.length;
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
LineNumberReader reader = new LineNumberReader(br);
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
int count =0;
line = br.readLine();
count++;
while(line!=null){
System.out.println(count+": "+line);
line = br.readLine();
count++;
int i=0;
if(count==num[i]){
int j=0;;
System.out.println(count);
String newtext = line.replace(line, VALUES[j]) + System.lineSeparator();
j++;
writer1.write(newtext);
}
i++;
writer1.append(line);
}
writer1.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
}
}
}
The expected output should look like this:
public class MyC{
AB
BC
CD
Sys.out.println("hi");
}
}
When I run the code, all lines appear on the same line.
You've done almost, I've updated your code with a map. Check this
int num[] = {3, 4, 5};
String[] values = new String[]{"AB", "BC", "CD"};
HashMap<Integer,String> lineValueMap = new HashMap();
for(int i=0 ;i<num.length ; i++) {
lineValueMap.put(num[i],values[i]);
}
FileInputStream fs = new FileInputStream("test.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("test1.txt");
int count = 1;
String line = br.readLine();
while (line != null) {
String replaceValue = lineValueMap.get(count);
if(replaceValue != null) {
writer1.write(replaceValue);
} else {
writer1.write(line);
}
writer1.write(System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.flush();
You're appending each line to the same string. You should add the line separator character at the end of each line as well. (You can do this robustly using System.getProperty("line.separator"))
you have not appended end line character.
writer1.append(line); is appending the data in line without endline character. Thus it is showing in one line. You might need to change it to:
writer1.append(line).append("\n");
Try This
package src;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {3,4,5};
String[] VALUES = new String[] {"AB","BC","CD"};
FileInputStream fs= new FileInputStream("C:\\Test\\ren.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Test\\ren1.txt");
String line;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
line = VALUES[index];
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
I have a text file that consists of several entries such as:
hello
there
my
name
is
JoeBloggs
How would I read the last five entries in descending order, i.e. from JoeBloggs - there
I currently have code to read the LAST LINE only:
public class TestLastLineRead {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream(file.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = null, tmp;
while ((tmp = br.readLine()) != null) {
strLine = tmp;
}
String lastLine = strLine;
System.out.println(lastLine);
in.close();
}
}
You can add the lines to a List, e.g. a LinkedList. When the list has more than five lines, remove the first/last.
List<String> lines = new LinkedList<String>();
for(String tmp; (tmp = br.readLine()) != null;)
if (lines.add(tmp) && lines.size() > 5)
lines.remove(0);
One very easy way would be to use the CircularFifoBuffer class from the Apache Commons Collections library. It's basically a list of a fixed size that discards old elements when it's full and you add new ones. So you'd create a CircularFifoBuffer of size 5, then add all the lines to it. At the end, it'd contain just the last five lines of the file.
we can use MemoryMappedFile for printing last 5 lines:
private static void printByMemoryMappedFile(File file) throws FileNotFoundException, IOException{
FileInputStream fileInputStream=new FileInputStream(file);
FileChannel channel=fileInputStream.getChannel();
ByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
buffer.position((int)channel.size());
int count=0;
StringBuilder builder=new StringBuilder();
for(long i=channel.size()-1;i>=0;i--){
char c=(char)buffer.get((int)i);
builder.append(c);
if(c=='\n'){
if(count==5)break;
count++;
builder.reverse();
System.out.println(builder.toString());
builder=null;
builder=new StringBuilder();
}
}
channel.close();
}
RandomAccessFile to print last 5 lines:
private static void printByRandomAcessFile(File file) throws FileNotFoundException, IOException{
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
int lines = 0;
StringBuilder builder = new StringBuilder();
long length = file.length();
length--;
randomAccessFile.seek(length);
for(long seek = length; seek >= 0; --seek){
randomAccessFile.seek(seek);
char c = (char)randomAccessFile.read();
builder.append(c);
if(c == '\n'){
builder = builder.reverse();
System.out.println(builder.toString());
lines++;
builder = null;
builder = new StringBuilder();
if (lines == 5){
break;
}
}
}
}
Try this code, a list of length 5 is scanned through all the lines, finally the list is reversed. I edited / modified your code, test it to see it's fully working.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) throws Exception
{
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 6)
bandWidth.remove(0);
}
ArrayList<String> reversedFive = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedFive.add(bandWidth.get(i));
in.close();
}
}
If all it really does have to do is print last 5 lines:
ArrayList<String> lines = new ArrayList<String>();
String tmp="";
while ((tmp = br.readLine()) != null) {
lines.add(tmp);
}
for (int i = lines.size()-5; i < lines.size(); i++) {
System.out.println(lines.get(i-1));
}
First you have to read the file line by line and add each line to a list. Once the file is read completely, you can print each element in the list in reverse order as shown below:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FileReader {
public static List<String> readFile() throws IOException {
List<String> fileContents = new ArrayList<String>();
FileInputStream fileInputStream = new FileInputStream("C:/Users/compaq/Desktop/file.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String strLine = null;
while((strLine=bufferedReader.readLine())!=null) {
fileContents.add(strLine);
}
fileInputStream.close();
return fileContents;
}
public static void printFileInReverse(List<String> fileContents, int numberOfLines) {
int counter = 0;
for(int i=(fileContents.size()-1);i>=0;i--) {
if(counter==numberOfLines) { break; }
System.out.println(fileContents.get(i));
counter++;
}
}
public static void main(String[] args) throws IOException {
List<String> fileContents = new ArrayList<String>();
fileContents = FileReader.readFile();
int numberOfLines = 5;// Number of lines that you would like to print from the bottom of your text file.
FileReader.printFileInReverse(fileContents, numberOfLines);
}
}
Try this.
This give for last 5 line.
public static void main(String[] args) throws IOException {
List<String > list =new ArrayList<String>();
FileInputStream in = new FileInputStream("C:/adminconsole.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine ="", tmp;
while ((tmp = br.readLine()) != null){
//strLine =tmp+"\n"+strLine;
list.add(tmp);
}
if(list.size()>5){
for (int i=list.size()-1; i>=(list.size()-5); i--) {
System.out.println(list.get(i));
}
}else{
for (int i=0; i<5; i++) {
System.out.println(list.get(i));
}
}
}
}
Follow This Code To Improve Core Java Logic By Using Collectios.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
public class REVERSE {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
try {
Scanner sc = new Scanner(new FileReader("input.txt"));
while (sc.hasNextLine()) {
al.add(sc.nextLine());
}
System.out.println(al.get(0));
System.out.println(al.get(1));
System.out.println(al.get(2));
System.out.println(al.get(3));
System.out.println(al.get(4));
Collections.reverse(al);
/*
* for (String s : al) { System.out.println(s); }
*/
System.out.println(al.get(0));
System.out.println(al.get(1));
System.out.println(al.get(2));
System.out.println(al.get(3));
System.out.println(al.get(4));
/*
* for (int i = 0; i < al.size(); i++) {
* System.out.println(al.get(i)); }
*/
} catch (FileNotFoundException e) {
}
}
}
Please try this code. It is working fine for me.
public static void main(String[] args)
{
try
{
int numOfLastline = 10;
BufferedReader reader = new BufferedReader(new FileReader("Text.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
reader.close();
System.out.println(lines);
String printedLine = null;
List<String> listForString = new ArrayList<String>();
for (int i = lines - 1; i >= (lines - numOfLastline); i--)
{
printedLine = (String) FileUtils.readLines(new File("Text.txt"), "ISO-8859-1").get(i);
System.out.println(printedLine);
listForString.add(printedLine);
}
System.out.println("\n\n============ Printing in Correct order =============\n\n");
Collections.reverse(listForString);
for (int k = 0; k < listForString.size() ; k++)
{
System.out.println(listForString.get(k));
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Note : Provide your needed last line numbers at numOfLastline and file [instead of this Text.txt].