How to write content on a text file using java? - java

i am having a program in java.which system.out some strings,i need to save each of them in a text file
it is showing in a format
ruo1 row2 row3
i want it in
row1
row2
row3
how can i do that in java?
import java.util.Arrays;
import java.io.*;
public class BruteForce {
public static FileOutputStream Output;
public static PrintStream file;
public static String line;
public static void main(String[] args) {
String password = "javabeanc";
char[] charset = "abcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 8);
String attempt = bf.toString();
while (true) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
writer.write(attempt+"\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
attempt = bf.toString();
System.out.println("Tried: " + attempt);
bf.increment();
}
}
private char[] cs; // Character Set
private char[] cg; // Current Guess
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
public String toString() {
return String.valueOf(cg);
}
}

Very quick code. I apologize if there are compile errors.
import java.io.FileWriter;
import java.io.IOException;
public class TestClass {
public static String newLine = System.getProperty("line.separator");
public static void main(String[] a) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
for(int i=0;i<3;i++){
writer.write(row+i+newLine);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

how about adding a new line character "\n" to each row ?

u can use PrintWriter pw;
pw.println(row+i)
in above instead of hard coding newLine

Using JDK 11 one can write:
public void writeToFile() {
String content = "Line 1\nLine 2";
Path path = Paths.get("./resources/sample-new.txt");
Files.writeString(path, content);
}

Related

OutOfMemoryError: Java heap space when trying to create ArrayList

I am trying to write a program which converts all G1 lines of a G code to lines which say MOVX (x-coordinate of G1 command)
Eg. G1 X0.1851 should become MOVX(0.1851)
At the moment the program is just appending the text file that has been read and printing the new code below the old one in the same text file.
The problem is that when I try to create an array list of the number after the X in the G-Code, I get a problem with the memory in the heap space overflowing.
I have added a clear() statement after each iteration of a line of the G-Code to try to prevent the array list becoming larger and larger but it keeps overflowing.
Here is my code:
package textfiles;
import java.io.IOException;
import java.util.ArrayList;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/blabla";
try {
ReadFile file = new ReadFile(file_name);
WriteFile data = new WriteFile(file_name, true);
String[] aryLines = file.OpenFile();
int i;
int j;
int y;
for (i=0; i < aryLines.length; i++ ) { //goes through whole text file
System.out.println( aryLines[ i ]);
if (i == 0) {
data.writeToFile("");
System.lineSeparator();
}
char[] ch = aryLines[ i ].toCharArray();
ArrayList<Character> num = new ArrayList<Character>();
String xCo = null;
boolean counterX = false;
if ((ch[0]) == 'G' && ch[1] == '1') {
for (j = 0; j < ch.length; j++) { //goes through each line of text file
for (y = 0; counterX == true; y++) {
num.add(ch[j]);
}
if (ch[j] == 'X') {
counterX = true;
}
else if (ch[j] == ' ') {
counterX = false;
}
}
xCo = num.toString();
data.writeToFile("MOVX (" + xCo + ")");
}
num.clear();
}
}
catch (IOException e) {
System.out.println( e.getMessage() );
}
System.out.println("Text File Written To");
}
}
I'd suggest to avoid reading data into memory and to use streaming instead.
Then function which converts lines could look like:
public void convertFile(String fileName, String tmpFileName) throws IOException {
try (FileWriter writer = new FileWriter(tmpFileName, true)){
Pattern pG1_X = Pattern.compile("^G1 X");
Files.newBufferedReader(Paths.get(fileName)).lines().forEach(line -> {
try {
double x = Double.parseDouble(pG1_X.split(line)[1]); // get coordinate
String newLine = String.format("MOVX(%f)\n",x); // attempt to replace coordinate format
writer.write(newLine);
} catch (Exception e) {
LOGGER.log(Level.WARNING, String.format("error wile converting line %s", line), e);
}
});
}
}
Testcase which demonstrates how it works:
package com.github.vtitov.test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.nio.file.StandardCopyOption;
#RunWith(Theories.class)
public class ReadWriteTest {
final static Logger LOGGER = Logger.getLogger(ReadWriteTest.class.getName());
public void convertFile(String fileName, String tmpFileName) throws IOException {
try (FileWriter writer = new FileWriter(tmpFileName, true)){
Pattern pG1_X = Pattern.compile("^G1 X");
Files.newBufferedReader(Paths.get(fileName)).lines().forEach(line -> {
try {
double x = Double.parseDouble(pG1_X.split(line)[1]); // get coordinate
String newLine = String.format("MOVX(%f)\n",x); // attempt to replace coordinate format
writer.write(newLine);
} catch (Exception e) {
LOGGER.log(Level.WARNING, String.format("error wile converting line %s", line), e);
}
});
}
}
#DataPoints static public Long[] fileSizes() {return new Long[]{100L,10_000L,1_000_000L}; }
#Theory
public void readWriteTest(Long fileSize) throws Exception {
TemporaryFolder folder = TemporaryFolder.builder().parentFolder(new File("target")).build();
folder.create();
File file = folder.newFile(UUID.randomUUID() + ".txt");
File tmpFile = folder.newFile(file.getName() + ".tmp");
createFile(fileSize, file);
String filePath = file.getPath();
LOGGER.info(String.format("created file %s of %d lines", filePath, fileSize));
String tmpFilePath = filePath + ".tmp";
convertFile(filePath, tmpFilePath);
LOGGER.info(String.format("file %s converted to %s", filePath, tmpFilePath));
//assert false;
Files.move(new File(tmpFilePath).toPath(), new File(filePath).toPath(),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
LOGGER.info(String.format("file %s moved to %s", tmpFilePath, filePath));
folder.delete();
}
private void createFile(long fileSize, File file) throws Exception {
try (FileWriter writer = new FileWriter(file,true)) {
Random rnd = new Random();
rnd.doubles(fileSize).forEach(l -> {
try { writer.write(String.format("G1 X%f\n", l)); } catch (IOException ignored) {}
});
}
}
}

How do I fix Illegal Start of Expressions with all of my methods?

I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.

How to print tagged values from a file?

I had to write a code to identify the language of tweets and to print out the tweets of a certain language. I have written the language identification part, but cannot get to print only the lines necessary.
Here is the code:
import java.io.*;
import java.util.*;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.functions.SMO;
import weka.classifiers.trees.RandomForest;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Lang_Detect
{
public static weka.classifiers.Classifier c;
public static HashMap<String,String> trigram=new HashMap<String,String>();
public static void initiate() throws Exception
{
c = loadModel("C:\\Users\\DIV\\ff\\Maithili\\nb.model"); // loads nb model
}
public static NaiveBayes loadModel(String path) throws Exception
{
NaiveBayes classifier;
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (NaiveBayes) ois.readObject();
ois.close();
return classifier;
}
public static void read_trigram()
{
try
{
FileInputStream fis = new FileInputStream("C:\\Users\\DIV\\ff\\Maithili\\Trigram.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String line;
while((line = br.readLine())!=null)
{
String words[]=line.split(":");
trigram.put(words[0].trim(), "");
}
fis.close();
}catch(IOException f){}
}
public static String feature_vector(String line)
{
String vector="";
String words[]=line.split(" ");
HashMap<String,String> local_word=new HashMap<String,String>();
for(int i=0;i<words.length;i++)
{
char ch[]=words[i].toCharArray();
for(int j=0;j<ch.length-2;j++)
{
local_word.put(ch[j]+""+ch[j+1]+""+ch[j+2], "");
}
}
for (Map.Entry<String, String> entry : trigram.entrySet())
{
if(local_word.containsKey(entry.getKey()))
{
vector+="1,";
}
else
{
vector+="0,";
}
}
return vector;
}
public static String lang_tag(String file) throws Exception
{
String tagged_sentence="";
int l=0,cntr=0;;
//String words[]=sentence.toLowerCase().split(" ");
StringBuffer str=new StringBuffer();
read_trigram();
// TODO Auto-generated method stub
int count=1;
str.append("#relation Language\n");
for (Map.Entry<String, String> entry : trigram.entrySet())
{
str.append("#attribute Trigram"+count+" numeric\n");
count++;
}
str.append("#attribute class {HN,NP,MT}\n");
str.append("#DATA\n");
try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String line;
while((line = br.readLine())!=null)
{
str.append(feature_vector(line)+"?\n");
}
fis.close();
}catch(IOException f){}
Global.file_update("C:\\Users\\DIV\\ff\\Maithili\\HN_NP_MT_Unlabelled.arff", str.toString());
Instances unlabeled = new Instances(
new BufferedReader(
new FileReader("HN_NP_MT_Unlabelled.arff")));
// set class attribute
unlabeled.setClassIndex(unlabeled.numAttributes() - 1);
Instances labeled = new Instances(unlabeled);
// label instances
for (int i = 0; i < unlabeled.numInstances(); i++)
{
double clsLabel = c.classifyInstance(unlabeled.instance(i));
String tag="";
if(clsLabel==0.0)
tag="HN";
else if(clsLabel==1.0)
tag="NP";
else if(clsLabel==2.0)
{
tag="MT";
Global.file_append("C:\\Users\\DIV\\ff\\Maithili\\Detected_Maithili_Tweets.txt", tag);
}
System.out.println(tag);
}
return tagged_sentence.trim();
}
public static void main(String[] args) throws Exception
{
initiate();
lang_tag("C:\\Users\\DIV\\ff\\Maithili\\tweets.txt");
}
}
As you can see in the lang_tag(), I want to print the lines which are tagged as MT, But I cannot get the lines in any particular variable.
Can someone help me?

Trying to read a text file using regex to check each line

I am trying to write a program that will allow a user to input a name of a movie and the program would then generate the date associated with. I have a text file that has date and the movies that pertain to it. I am reading the file via Scanner and I created a movie class that stores an ArrayList and String for movies and date, respectively. I am having trouble with reading the files. Can anyone please assist me. Thank you!
Here is a part of the text file:
10/1/2014
Der Anstandige
"Men, Women and Children"
Nas: Time is Illmatic
10/2/2014
Bang Bang
Haider
10/3/2014
Annabelle
Bitter Honey
Breakup Buddies
La chambre bleue
Drive Hard
Gone Girl
The Good Lie
A Good Marriage
The Hero of Color City
Inner Demons
Left Behind
Libertador
The Supreme Price
Here is my movie class
import java.util.ArrayList;
public class movie
{
private ArrayList<String> movies;
private String date;
public movie(ArrayList<String> movies, String date)
{
this.movies = movies;
this.date = date;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public ArrayList<String> getMovies()
{
return movies;
}
}
Here is the readFile class
package Read;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class readFile
{
public static List<movie> movies;
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[]args)
{
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
try
{
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine())
{
System.out.println("Hello");
//movies
if(!sc.nextLine().matches(regex2))
{
i = sc.nextLine();
System.out.println("Hello2");
System.out.println(i);
}
//date
while(sc.nextLine().matches(regex1))
{
System.out.println("Hello3");
if(!sc.nextLine().matches(regex1))
{
j = sc.nextLine();
mov.add(sc.nextLine());
System.out.println("Hello4");
}
}
movie movie = new movie(mov,i);
movies.add(movie);
}
// sc.close();
}
catch(Exception e)
{
System.out.println("CANT");
}
}
}
You shouldn't be calling sc.nextLine () in every check. Every NextLine () call reads next line.This means that you are checking one line and processing next line
package com.stackoverflow.q26269799;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFile {
public static List<Movie> movies = new ArrayList<Movie>();
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[] args) {
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
if ( !f.exists()) {
System.err.println("file path not specified");
}
try {
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
System.out.println("Hello");
// movies
String nextLine = sc.nextLine();
if (nextLine != null) {
if ( !nextLine.matches(regex2)) {
i = nextLine;
System.out.println("Hello2");
System.out.println(i);
}
// date
while (nextLine != null && nextLine.matches(regex1)) {
System.out.println("Hello3");
if ( !nextLine.matches(regex1)) {
j = nextLine;
mov.add(nextLine);
System.out.println("Hello4");
}
nextLine = sc.nextLine();
}
}
Movie movie = new Movie(mov, i);
movies.add(movie);
}
// sc.close();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
This is needed: //movies = new ArrayList<movie>();
Every time you call nextLine it will move the scanner point to the next line. So call it once a time and check if it match those regex. String nextLine = sc.nextLine();
Please check you whether the file path is specified.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class ReadFile
{
Map<String, String> movies;
public static void main(String[] args) throws IOException
{
ReadFile readFile = new ReadFile();
readFile.movies = new TreeMap<>();
try
{
readFile.importData();
printf(readFile.queryData("Der Anstandige"));
printf(readFile.queryData("Bitter"));
printf(readFile.queryData("blah"));
printf(readFile.queryData("the"));
}
catch(IOException e)
{
throw(e);
}
}
void importData() throws IOException, FileNotFoundException
{
LineNumberReader reader = null;
File file = new File("c:/movie_release_dates.txt");
try
{
reader = new LineNumberReader(new FileReader(file), 1024*64); //
String line;
String date = null, movie = null;
while((line = reader.readLine()) != null)
{
line = line.trim();
if(line.equals("")) continue;
if(line.matches(PATTERN_DATE))
{
date = line;
date = strf("%s/%s",
date.substring(date.length() - 4),
date.substring(0, date.length() - 5));
continue;
}
else
{
movie = line.trim();
}
movies.put(movie, date);
}
}
catch(FileNotFoundException e)
{
throw(e);
}
finally
{
reader.close();
}
}
String queryData(String title)
{
String regex = "(?i)" + title.replaceAll("\\s", "\\s+");
String[] matches = new String[movies.size()];
int i = 0; for(Entry<String , String> movie : movies.entrySet())
{
String key = movie.getKey();
String val = movie.getValue();
if(key.matches(regex))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
else if(key.toUpperCase().trim()
.contains(title.toUpperCase().trim()))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
}
String string = "";
if(matches[0] == null)
{
string = "Not found\n";
}
else
{
i = 0; while(matches[i] != null)
{
string += matches[i++] + "\n";
}
}
return string;
}
final String strf(String arg0, Object ... arg1)
{
return String.format(arg0, arg1);
}
final static void printf(String format, Object ... args)
{
System.out.printf(format, args);
}
final static void println(String x)
{
System.out.println(x);
}
final String PATTERN_DATE = "\\d{1,2}\\/\\d{1,2}\\/\\d{4}";
}
Console output:
{movie=Der Anstandige, date=2014/10/1}
{movie=Bitter Honey, date=2014/10/3}
Not found
{movie=The Good Lie, date=2014/10/3}
{movie=The Hero of Color City, date=2014/10/3}
{movie=The Supreme Price, date=2014/10/3}

How to print all method declaration and invocation from ASTParser

I want to print all the method invocations within all methods of a Class. I am using ASTParser. Following is my code
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import java .io.*;
public class ASTParserDemo {
public static void main(String[] args) {
ASTParserDemo demo = new ASTParserDemo();
String rawContent = demo.readFile();
//String rawContent = "public class HelloWorld { public String s = \"hello\"; public static void main(String[] args) { HelloWorld hw = new HelloWorld(); String s1 = hw.s; } }";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(rawContent.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
AST ast = cu.getAST();
IdentifierVisitor iv = new IdentifierVisitor();
cu.accept(iv);
}
public String readFile() {
StringBuffer fileContent = new StringBuffer();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\research\\android-projects\\AsyncSearch.java"));
while ((sCurrentLine = br.readLine()) != null) {
//System.out.println(sCurrentLine);
fileContent.append(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return fileContent.toString();
}
}
import org.eclipse.jdt.core.dom.*;
import java.util.*;
public class IdentifierVisitor extends ASTVisitor {
private Vector<String> identifiers = new Vector<String>();
public Vector<String> getIdentifiers(){
return identifiers;
}
public boolean visit(MethodDeclaration m){
System.out.println("METHOD DECLARATION : " + m);
return true;
}
public boolean visit(MethodInvocation m){
System.out.println("METHOD INVOCATION : " + m);
return true;
}
}
the output is showing only one method declaration. Please let me know how do I print all method invocations within all declared methods. Thanks
You're not using a good method to retrieve the string representation of your source code. You can use an alternative method for read a file from your path and return a string representation of source:
public static String readFileToString(String filePath) throws IOException {
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
// System.out.println(numRead);
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
Remember to always check whether it is an actual file before calling readFileToString(filePath) eg:
String filePath = file.getAbsolutePath();
if (file.isFile ()))
String source = readFileToString(filePath)
Alternatively you can print the contents of rawContent returned from your method readFile and check that the code you want to parse is actually the same as what you mean.

Categories