How to read a file from end to the beginning? - java

How to read file from end to the beginning my code,
try
{
String strpath="/var/date.log";
FileReader fr = new FileReader(strpath);
BufferedReader br = new BufferedReader(fr);
String ch;
String[] Arr;
do
{
ch = br.readLine();
if (ch != null)
out.print(ch+"<br/>");
}
while (ch != null);
fr.close();
}
catch(IOException e){
out.print(e.getMessage());
}

You can use RandomAccessFile class. Either just read in loop from file length to 0, or use some convenience 3rd party wraps like http://mattfleming.com/node/11

If you need print lines in reverse order:
Read all lines to list
Reverse them
Write them back
Code:
List<String> lines = new ArrayList<String>();
String curLine;
while ( (curLine= br.readLine()) != null) {
lines.add(curLine);
}
Collections.reverse(lines);
for (String line : lines) {
System.out.println(line);
}

If you don't want to use temporary data(for reversing the file) you should use RandomAccessFile class.
In other case you can read and store the whole file in memory, then reversing it contents.
List<String> data = new LinkedList<String>();
If you need lines in reverse order, insted of:
out.print(ch+"<br/>");
do
data.add(ch);
And after reading the whole file you can use
Collections.reverse(data);
If you need every symbol to be in reverse order, you can use type Character instead of String and read not the whole line but only one symbol.
After that simply reverse your data.
P.S. To print (to system output stream for example) you should iterate over each item in collection.
for (String line : data) {
out.println(line);
}
If you use just out.print(data) this will call data.toString() method and print out its result. Standart implementation of toString() will not work as you expected. It will return something like object type and number.

Related

split method to output values under each other when reading from a file

My code works fine however it prints the values side by side instead of under each other line by line. Like this:
iatadult,DDD,
iatfirst,AAA,BBB,CCC
I have done a diligent search on stackoverflow and none of my solution's seem to work. I know that I have to make the change while the looping is going on. However none of the examples I have seen have worked. Any further understanding or techniques to achieve my goal would be helpful. Whatever I am missing is probably very small. Please help.
String folderPath1 = "C:\\PayrollSync\\client\\client_orginal.txt";
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
if(line.contains("fooa")||line.contains("foob")){
fileContents.add(line);
}
//---------------------------------------
}
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents);
Add a Line Feed before you add to fileContents.
fileContents.add(line+"\n");
By printing the list directly as you are doing you are invoking the method toString() overridden for the list which prints the contents like this:
obj1.toString(),obj2.toString() .. , objN.toString()
in your case the obj* are of type String and the toString() override for it returns the string itself. That's why you are seeing all the strings separated by comma.
To do something different, i.e: printing each object in a separate line you should implement it yourself, and you can simply append the new line character('\n') after each string.
Possible solution in java 8:
String result = fileContents.stream().collect(Collectors.joining('\n'));
System.out.println(result);
A platform-independent way to add a new line:
fileContents.add(line + System.lineSeparator);
Below is my full answer. Thanks for your help stackoverflow. It took me all day but I have a full solution.
File file = new File (folderPath1);
ArrayList<String> fileContents = new ArrayList<>(); // holds all matching client names in array
try {
BufferedReader reader = new BufferedReader(new FileReader(file));// reads entire file
String line;
while (( line = reader.readLine()) != null) {
String [] names ={"iatdaily","iatrapala","iatfirst","wpolkrate","iatjohnson","iatvaleant"};
if (Stream.of(names).anyMatch(line.trim()::contains)) {
System.out.println(line);
fileContents.add(line + "\n");
}
}
System.out.println("---------------");
reader.close();// close reader
} catch (Exception e) {
System.out.println(e.getMessage());
}

How do I use BufferedReader to read lines from a txt file into an array

I know how to read in lines with Scanner, but how do I use a BufferedReader? I want to be able to read lines into an array. I am able to use the hasNext() function with a Scanner but not a BufferedReader, that is the only thing I don't know how to do. How do I check when the end of the file text has been reached?
BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));
String[] fileRead = new String[2990];
int count = 0;
while (fileRead[count] != null) {
fileRead[count] = reader.readLine();
count++;
}
readLine() returns null after reaching EOF.
Just
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. )
The documentation states that readLine() returns null if the end of the stream is reached.
The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array.
If you plan to read all the file's content, you can use Files.readAllLines instead:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
using readLine(), try-with-resources and Vector
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
{
String line;
Vector<String> fileRead = new Vector<String>();
while ((line = bufferedReader.readLine()) != null) {
fileRead.add(line);
}
} catch (IOException exception) {
exception.printStackTrace();
}

Read text containing multiple line using bufferedreader

I would like to know how to read a text file containing multiple lines in java using BufferedStreamReader.
Every line has two words separated by (;) and I want to use split() String operation to separate the 2 words. I also need to compare each word to a word in a master arraylist.
I'm having problems to continue.
Here's my code:
{
FileInputStreamReader f = new FileInputStreamReader(C://Desktop/test.txt);
InputStreamReader reader = new InputStreamReader(f);
BufferedReader Buff = new BufferedReader (reader);
String Line = buff.readLine();
String t[] = Line.split(;);
}
Replace
String Line = Buff.readLine();
with
// buffer for storing file contents in memory
StringBuffer stringBuffer = new StringBuffer("");
// for reading one line
String line = null;
// keep reading till readLine returns null
while ((line = Buff.readLine()) != null) {
// keep appending last line read to buffer
stringBuffer.append(line);
}
Now, you have read the complete file into StringBuffer, you do whatever you want.
Hope this helps.
Try
while((line=buff.readLine())!=null){
System.out.println(line);
}
You need a while loop to read all the lines.
Here is an example http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
You can use BufferedReader to loop through each of the line encountered within the specified file. In order to get your words split by a ";", you can use .split and can store the resulting array in a list.
Finally, combine all the lists to a single list which would inturn hold all the words present in your file.
List<String> words = Arrays.asList(line.split(";"));
list.addAll(words);
Now you would want to compare the retrieved list against a Master list containing all your records.
// Compare the 2 lists, assuming your file list has less number of
// records
masterList.removeAll(list);
The above statement can be used in reverse too; in case the file holds the master list of words. Alternatively, you can store the 2 lists in temporary lists and compare in whatsoever way your require.
Here is the complete code:
public static void main(String[] args) {
String line;
// List of all the words read from the file
List<String> list = new ArrayList<String>();
// Your original mast list of words against which you want to compare
List<String> masterList = new ArrayList<String>(Arrays.asList("cleaner",
"code", "java", "read", "write", "market", "python", "snake",
"stack", "overflow"));
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("testing.txt"));
while ((line = reader.readLine()) != null) {
// Add all the words split by a ; to the list
List<String> words = Arrays.asList(line.split(";"));
list.addAll(words);
}
// Compare the 2 lists, assuming your file list has less number of
// records
masterList.removeAll(list);
System.out.println(masterList);
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
File which I have created looks like:
cleaner;code
java;read
write;market
python;snake
The output of the above code:
[stack, overflow]

Initialising an array of objects from a CSV file

This problem takes a bit of explaining, I'll try to be as concise as possible:
I have am trying to initalise an array of Can objects, these objects only have 2 fields (both Strings): name, manufacturer
I am trying to initialise the fields by reading from a CSV file with the following format:
Tomatoes,Heinz
Legumes,Jerry
(no space between the lines, it's being formatted like that on this site for some reason)
The first string in each row is the value I want to be the name, the 2nd is the manufacturer.
So I've created a method to read each line of the CSV, which passes each line to a tokenizer method to extract single values:
private void readFile (String inFilename) {
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int lineNum;
String line;
try {
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
lineNum = 0;
line = bufRdr.readLine();
while {line != null) {
lineNum++;
processLine(line); //passes line to tokenizer
line = bufRdr.readLine();
}
fileStrm.close();
}
catch (IOException e) {
if (fileStrm != null) {
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
The lines are passed to this tokenizer method:
private String processLine(String csvRow) {
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ",");
while (strTok.hasMoreTokens()) {
thisToken = strTok.nextToken();
}
}
And that's where I get a bit stuck. To initialise my array I think I'd need a for loop, something like
for (int i=0; i<=array.length;i++)
{
array[i].name = readFile("filename.csv");
array[i].manufacturer = readFile("filename.csv");
}
But obviously this will not work. Can anyone suggest how I can go about this? I'd prefer to keep the code mostly intact and figure out a solution using the existing code.
Thanks
First thing: -
You are calling processLine(line);, but are not returning the token read from this method.. So, the token obtained in this method in engulped there only.. So, you should return something from that method..
Second:-
array[i].name = readFile("filename.csv");
array[i].manufacturer = readFile("filename.csv");
In the above code, you are calling readFile() each time for the two attributes.. So, even if you return somthing, these two attributes will be initialized to same value.. Because each time you are starting reading file from scratch..
Third thing: -
In fact your above code will not compile.. Because you are assigning the value of readFile() (which is actually not returning anything) to array.. So give a return type to this method.. It would be String.. And returning the tokens read..
EDIT: -
* I would suggest, you can use split() method of String class.. Tokenizer is not needed here, for justsplittingaround a singlecomma(,)`
Also, rather than using an array, you can use ArrayList, in which you can add your newly created object on the fly.. That way, you will not have to fix the size of array.. (And this is what you will want, as you don't know how much line you will have in your file right?)
Here's what you can do: -
Call the method readFile from somewhere, probably main()
readFile("filename.csv")
In your readFile() method, you can iterate over file to create an ArrayList like this: -
List<Can> yourList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] wordRead = line.split(',');
yourList.add(new Can(wordRead[0], wordRead[1]));
}
I assume, Can is the name of your class as you stated in your problem..

How can I recognize a special delimiter string when reading from a file of strings?

I want to read strings from a file. When a certain string (><) is found, I want to start reading integers instead, and convert them to binary strings.
My program is reading the strings in and saving them in an ArrayList successfully, but
it does not recognise the >< symbol and therefore the reading of the binary strings is not successful.
The Code
try {
FileInputStream fstream = new FileInputStream(fc.getSelectedFile().getPath());
// Get the object of DataInputStream
DataInputStream ino = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(ino));
String ln;
String str, next;
int line, c =0;
while ((ln = br.readLine()) != null) {
character = ln;
System.out.println(character);
iname.add(ln); // arraylist that holds the strings
if (iname.get(c).equals("><")) {
break; // break and moves
// on with the following while loop to start reading binary strings instead.
}
c++;
}
String s = "";
// System.out.println("SEQUENCE of bytes");
while ((line = ino.read()) != -1) {
String temp = Integer.toString(line, 2);
arrayl.add(temp);
System.out.println("telise? oxii");
System.out.println(line);
}
ino.close();
} catch (Exception exc) { }
The file I'm trying to read is for example:
T
E
a
v
X
L
A
.
x
"><"
sequence of bytes.
Where the last part is saved as bytes and in the textfile appears like that. no worries this bit works. all the strings are saved in a new line.
< is two characters and iname.get(c) is only one character.
What u should do is test if ln equals > and then another test if the next character equals < . If both test pass then break out of the loop.
you will have to becarefull
Use a Scanner. It allows you to specify a delimiter, and has methods for reading input tokens as String or int.
Could you not do something like:
while ((ln = br.readLine()) != null){
character=ln;
System.out.println(character);
//
// Look for magic characters >< and stop reading if found
//
if (character.indexOf("><") >= 0) {
break;
}
iname.add(ln);
}
This would work if you didn't want to add the magic symbol to your ArrayList. Your code sample is incomplete - if you're still having trouble you'd need to post the whole class.

Categories

Resources