I am using the following function to find all the line-numbers which has word as a substring.
public ArrayList<Integer> find(String word, File text) throws IOException {
LineNumberReader rdr = new LineNumberReader(new FileReader(text));
ArrayList<Integer> results = new ArrayList<Integer>();
try {
String line = rdr.readLine();
if (line.contains(word)) {
results.add(rdr.getLineNumber());
}
} finally {
rdr.close();
}
return results;
}
But, when I call the above function as under, I get the size of the lineNumberList as 0 (Assume that the file contains at least one occurrence of word as substring )
IProject project = (IProject)((IAdaptable)firstElement).getAdapter(IProject.class);
IFile manifest = project.getFile("AndroidManifest.xml");
File manifestfile = manifest.getRawLocation().makeAbsolute().toFile();
ArrayList<Integer> lineNumberList = new ArrayList<Integer>();
lineNumberList = find(PermissionInfo[0].trim(), manifestfile);
Loop through the items i.e.
public ArrayList<Integer> find(String word, File text) throws IOException {
LineNumberReader rdr = new LineNumberReader(new FileReader(text));
ArrayList<Integer> results = new ArrayList<Integer>();
try {
String line = rdr.readLine();
while(line != null){
if (line.contains(word)) {
results.add(rdr.getLineNumber());
}
line = rdr.readLine();
}
} finally {
rdr.close();
}
return results;
}
If you are having multiple lines in the file, a for loop might be needed to wrap getLine().
Related
I'm trying to figure out how to make a function in JAVA that searches through a document line per line:
First I initialize the file and a reader, then convert each line to a string in an ArrayList; after that I try to check the ArrayList against a String to then return the position of the ArrayList as a string.
So for example I have a text containing:
1 - Somewhere over the rainbow
2 - Way up high.
Converted to ArrayList, if then searched for: "Somewhere"; then it should return the sentence "Somewhere over the rainbow";
Here is the code I tried; but it keeps returning 'null';
String FReadUtilString(String line) {
File file = new File(filepath);
ArrayList<String> lineReader = new ArrayList<String>();
System.out.println();
try {
Scanner sc = new Scanner(file);
String outputReader;
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
sc.close();
for(int count = 0; count < lineReader.size(); count++) {
if(lineReader.get(count).contains(line)){outputReader = lineReader.get(count);}
}
} catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
I refactor your code a bit, but I keep your logic, it should work for you:
String FReadUtilString(String line, String fileName){
File file = new File(fileName);
List<String> lineReader = new ArrayList<>();
String outputReader = "";
try (Scanner sc = new Scanner(file))
{
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
for (int count = 0; count < lineReader.size(); count++){
if (lineReader.get(count).contains(line)){
outputReader = lineReader.get(count);
}
}
}
catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
NOTE: I used the try-with-resource statement to ensure the closing of the Scanner.
A more succinct version:
String fReadUtilString(String line, String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
return lines.filter(l -> l.contains(line)).findFirst();
}
catch (Exception linereadeline) {
System.out.println(linereadeline); // or just let the exception propagate
}
}
What I'm looking to do here is process a log file, in my case it's squid's access.log. I want to have my program take a look at the first 'word' in the file, which is the time in Unix format of when the URL was accessed. In other parts of the program, I designed a time class, which gets the time the program was last run in Unix time, and I want to compare this time to the first word in the file, which happens to be a Unix time.
My initial thinking on how to do this is that I process the file, store it in array, then based on the first word in the file, omit the lines by removing it from the array that the processed file is in, and put it in another array
Here's what I've got so far. I'm pretty sure that I'm close, but this is the first time that I've done file processing, so I don't exactly know what I'm doing here.
private void readFile(File file) throws FileNotFoundException, IOException{
String[] lines = new String[getLineCount(file)];
Long unixTime = time.getUnixLastRun();
String[] removedTime = new String[getLineCount(file)];
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
int i = 0;
for(String line; (line = br.readLine()) != null; i++) {
lines[i] = line;
}
}
for(String arr: lines){
System.out.println(arr);
}
}
private void readFile(File file) {
List<String> lines = new ArrayList<String>();
List<String> firstWord = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
// Adds the entire first line
lines.add(sCurrentLine);
// Adds the first word
firstWord.add(sCurrentLine.split(" ")[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
If you want you can use your arrays.
private void readFile(File file) throws FileNotFoundException, IOException {
String[] lines = new String[getLineCount(file)];
Long unixTime = time.getUnixLastRun();
String[] removedTime = new String[getLineCount(file)];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
int i = 0;
for (String line; (line = br.readLine()) != null; i++) {
lines[i] = line;
}
}
ArrayList<String> logsToBeUsed = new ArrayList<String>();
for (String arr : lines) {
//Gets the first word from the line and compares it with the current unix time, if it is >= unix time
//then we add it to the list of Strings to be used
try{
if(Long.parseLong(getFirstWord(arr)) >= unixTime){
logsToBeUsed.add(arr);
}
}catch(NumberFormatException nfe){
//Means the first word was not a float, do something here
}
}
}
private String getFirstWord(String text) {
if (text.indexOf(' ') > -1) {
return text.substring(0, text.indexOf(' '));
} else {
return text;
}
}
This is the answer according to the code you posted. This can be done more efficiently as you can use an ArrayList to store the lines from the file rather than first reading the line number getLineCount(file) as you open the file twice. And in the for loop you are declaring the String object again and again.
I'm really stucked on this one. I'm wondering if it's possible to exclude all the elements from arraylist on reading a file? Thank you in advance!
I have elements on my arraylist(excludelist) like this:
test1
test2
test3
And I have csv data on my file(readtest) like this:
test1,off
test2,on
test3,off
test4,on
so what i'm expecting is to exclude all the data from arraylist in while loop then will be output like this :
test4,on
This is my code:
String exclude = "C:\\pathtomyexcludefile\\exclude.txt";
String read = "C:\\pathtomytextfile\\test.txt";
File readtest = new File(read);
File excludetest = new File(exclude);
ArrayList<String> excludelist = new ArrayList();
excludelist.addAll(getFile(excludetest));
try{
String line;
LineIterator it = FileUtils.lineIterator(readtest,"UTF-8");
while(it.hasNext()){
line = it.nextLine();
//determine here
}
catch(Exception e){
e.printStackTrace();
}
public static ArrayList<String> getFile(File file) {
ArrayList<String> data = new ArrayList();
String line;
try{
LineIterator it = FileUtils.lineIterator(file,"UTF-8");
while(it.hasNext()){
line = it.nextLine();
data.add(line);
}
it.close();
}
catch(Exception e){
e.printStackTrace();
}
return data;
}
There might be more efficient ways to do this, but you can inspect each line you're reading using String.startsWith against each element in the excludeList. If the line does not start with a to-be-excluded word, add it to the approvedLines list.
String exclude = "C:\\pathtomyexcludefile\\exclude.txt";
String read = "C:\\pathtomytextfile\\test.txt";
File readtest = new File(read);
File excludetest = new File(exclude);
List<String> excludelist = new ArrayList<>();
excludelist.addAll(getFile(excludetest));
List<String> approvedLines = new ArrayList<>();
LineIterator it = FileUtils.lineIterator(readtest, "UTF-8");
while (it.hasNext()) {
String line = it.nextLine();
boolean lineIsValid = true;
for (String excludedWord : excludelist) {
if (line.startsWith(excludedWord)) {
lineIsValid = false;
break;
}
}
if (lineIsValid) {
approvedLines.add(line);
}
}
// check that we got it right
for (String line : approvedLines) {
System.out.println(line);
}
If your excluded elements are a a String objects, you can try something like this:
while(it.hasNext()){
line = it.nextLine();
for(String excluded : excludelist){
if(line.startsWith(excluded)){
continue;
}
}
}
Here is my code. The input consists of names of anime(japanese cartoons) which i have stored it in testfile in anime.txt and I am arranging them in alphabetical order and writing it back into another file name animeout.txt.
The input file does not contain any comma or square bracket but the output file has it.
public class Main {
public static ArrayList<String> read(String filePath) throws IOException {
ArrayList<String> names = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
int numRead = 0;
String line;
while ((line = reader.readLine()) != null) {
names.add(line + "\n");
numRead++;
}
System.out.println("\n\n count " +numRead);
reader.close();
System.out.println(names);
return names;
}
public static void write(ArrayList<String> input) throws IOException
{
File file = new File("Animeout.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(input);
writer.flush();
writer.close();
}
public static void main(String args[]) throws IOException
{
ArrayList<String> names2 = new ArrayList<String>();
String path= "anime.txt";
String test;
names2 = read(path);
Collections.sort(names2, null);
// System.out.println(names2);
write(names2);
}
}
Input file has about 200 lines. Below is just a small example
One piece
Naruto/naruto shippuden
Bleach
Fullmetal alchemist brotherhood
Fate/stay night
Fairy tale
Blue exorcist
Soul eater
Death note
Output file contains , and [
count 105
[11 eyes
, A certain magical index
, A certain magical index II
, Aldnoah.Zero
, Angel beats!
, Another
, Asu no yoichi
, Bay blade
, Beelzebub
, Ben-To
String str = "[12,34,45]";
String out = str.replaceAll(",|\\[|\\]","");
output:
123445
Why are you using a ObjectOuputStream? That is intended for when you want to serialise Java objects and restore them later. I don't see why you need it here.
Just use a FileWriter, like so:
public static void write(ArrayList<String> input) throws IOException
{
try
{
File file = new File("Animeout.txt");
FileWriter fw = new FileWriter(file);
for (int i = 0; i < input.size(); i++) {
fw.append(input.get(i) + "\n");
}
}
finally
{
try {
if (fw != null)
fw.close();
}
catch (Exception e) {
// ignore
}
}
}
Your write method is unfortunate. Try something like this instead (and remove the + "\n" when reading the lines):
public static void write(ArrayList<String> lines) throws IOException
{
File file = new File("Animeout.txt");
PrintStream ps = null;
try {
ps = new PrintStream(file);
for (final String line : lines) {
ps.println(line);
}
} finally {
if (ps != null) { ps.close(); }
}
}
The ObjectOutputStream you are using is not appropriate for simply writing lines of text.
Finally, if all you want to do is sorting the lines of a text file, at least on a POSIX system, you can just do it with
$ sort anime.txt > Animeout.txt
from the command line.
I want to split file as Header with detail in a list based on sequence.
want to split the text file using Header and detail I tried something like this but doesn't help.
I wanted to call previous iteration of iterator but I couldn't...
File :
H>>>>>>
L>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>>
L>>>>>>>
H>>>>>>>
L>>>>>>> ...
I wanted :
List 1 with H , L , L ,L
List 2 with H , L , L
List 3 with H , L
Code Tried :
List<String> poString = new ArrayList<String>();
if(poString !=null && poString.size() > 0)
{
ListIterator<String> iter = poString.listIterator();
while(iter.hasNext())
{
String tempHead = iter.next();
List<String> detailLst = new ArrayList<String>();
if(tempHead.startsWith("H"))
{
while(iter.hasNext())
{
String detailt = iter.next();
if(!detailt.startsWith("H"))
detailLst.add(detailt);
else
{
iter.previousIndex();
}
}
}
}
Try this (untested):
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
List<StringBuilder> myList = new List<StringBuilder>();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line[0] == 'H')
{
myList.add(sb);
sb = new StringBuilder();
}
sb.append(line[0]);
line = br.readLine();
}
} finally {
br.close();
}
as far as I understood, eventually how many H..lines in your file, how many List<String> would you want to have.
If you don't know the exact number, (in your example, it is 3) then you have a List of List (List<List<String>>).
//read the file, omitted
List<List<String>> myList = new ArrayList<<List<String>>();
List<String> lines = null;
boolean createList = false;
while (line != null) {
if (line.startsWith("H")){
myList.add(lines);
lines = new ArrayList<String>();
}
//if the 1st line of your file not starting with 'H', NPE, you have to handle it
lines.add(line);
line=readnextlineSomeHow(); //read next line
}
the above codes may not work out of box, but it gives you the idea.
Try this, I've tried a little on my own and it works
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
ArrayList<ArrayList<String>> result = new ArrayList<> ();
int numlines =0;
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
if (line.startsWith("H"))
{
result.add(new ArrayList<String>());
result.get(numlines).add("H");
line = br.readLine();
while(line != null && !line.startsWith("H")){
if(line.startsWith("L")) result.get(numlines).add("L");
line = br.readLine();
}
++numlines;
}
else line = br.readLine();
}
} finally {
br.close();
}
You can use this..
public static void main(String a[]) throws Exception
{
ArrayList<String> headers=new ArrayList();
ArrayList<String> lines=new ArrayList();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
File f= new File("inputfile.txt");
Scanner scanner = new Scanner(f);
try {
while (scanner.hasNextLine()){
String ss=scanner.nextLine();
String key= String.valueOf(ss.charAt(0));
if ( map.containsKey(key))
{
ArrayList<String> temp=(ArrayList) map.get(key);
temp.add(ss);
map.put(key, temp);
}
else
{
ArrayList<String> temp= new ArrayList();
temp.add(ss);
map.put(key, temp);
}
}
}
catch(Exception e)
{
throw e;
}
}