How to read last 5 lines of a .txt file into java - java

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

Related

How to print text file left to right, and then upside down?

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

I am trying to count characters from a within file

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

How do you store each value separately using comma then they store into separate array?

A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.

Reading data from a text file in Java

I have a problem in reading data from a text file and put it in 2 dimensional array. The sample of dataset is:
1,2,3,4,5,6
1.2,2.3,4.5,5.67,7.43,8
The problem of this code is that it just read the first line and does not read the next lines. Any suggestion is appreciated.
package test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1{
public static void main(String args[])throws FileNotFoundException, IOException{
try{
double[][] X = new double[2][6];
BufferedReader input = new BufferedReader(new FileReader(file));
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
int rowCounter = 0;
while ((line = input.readLine())!= null) {
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
}
}
}
Have you tried the Array utilities? Something like this:
while ((line = input.readLine())!= null) {
List<String> someList = Arrays.asList(line.split(","));
//do your conversion to double here
rowCounter++;
}
I think the blank line might be throwing your for loop off
The only place that your temp array is being assigned is before your while loop. You need to assign your temp array inside the loop, and don't read from the BufferedReader until the loop.
String[] temp;
String line;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine())!= null) {
temp = line.split(delims); // Moved inside the loop.
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
Try:
int rowCounter = 0;
while ((line = input.readLine())!= null) {
String [] temp;
String line = input.readLine();
String delims = ",";
temp = line.split(delims);
for(int i = 0; i<6; i++){
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
...
readLine expects a new line character at the end of the line. You should put a blank line to read the last line or use read instead.
I couldn't run the code, but one of your problems is that you were only splitting the first text line.
package Test1;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Test1 {
public static void main(String args[]) {
try {
double[][] X = new double[2][];
BufferedReader input = new BufferedReader(new FileReader(file));
String line = null;
String delims = ",";
int rowCounter = 0;
while ((line = input.readLine()) != null) {
String[] temp = line.split(delims);
for (int i = 0; i < temp.length; i++) {
X[rowCounter][i] = Double.parseDouble(temp[i]);
}
rowCounter++;
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
}
}
}
I formatted your code to make it more readable.
I deferred setting the size of the second element of the two dimensional array until I knew how many numbers were on a line.

Replace lines in File with another string

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 {
}
}
}

Categories