I am trying to make a class for generating random words. So far my choices are Scanner or a BufferReader I am guessing.
This is the code that I think is most efficient however when I run I get null.
Also will a public return randomWord getter grant access to the word in main class?
private static final String filepath = "/assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words = new ArrayList<String>();
public void WordGenerator() {
rand = new Random();
String line;
try {
InputStream WordsFile = getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(WordsFile));
if(!br.ready()){
System.out.println("No File");
}
else while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
}
catch (IOException e) {
System.out.println("Something is wrong");
}
int size = words.size();
Random rn = new Random();
int randWord = rn.nextInt(size);
randomWord = words.get(randWord);
System.out.println(randomWord);
}
}
I think what you really need to read your file is to remove the InputStream line and just replace the BufferedReader with this one:
BufferedReader br = new BufferedReader(new FileReader(filepath));
So your code will look like this:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class WordGeneratorClass
{
private static final String filepath="../assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words=new ArrayList<String>();
public void WordGenerator()
{
rand=new Random();
String line;
try
{
BufferedReader br = new BufferedReader(new FileReader(filepath));
if(!br.ready())
{
System.out.println("No File");
}
else while((line=br.readLine())!=null)
{
words.add(line);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
int size=words.size();
Random rn=new Random();
int randWord=rn.nextInt(size);
randomWord=words.get(randWord);
System.out.println(randomWord);
}
public static void main(String args[])
{
WordGeneratorClass gen = new WordGeneratorClass();
gen.WordGenerator();
}
}
Ensure that your assets/words.txt exist.
Edit
Seems that the problem was also related to the path of your words.txt. The above code assumes that the assets/words/words.txt is in the same directory with the source code. For more information, please have a look here.
Related
file path is not working, input1.txt is located in the same directory as library.java.
What should i do to correct it ?
How should i give path so that it read thr text file ?
package SimpleLibrarySystem;
import java.time.LocalDateTime;
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Library
{
ArrayList <Book> var = new ArrayList<Book>();
HashMap<Book, LocalDateTime> var1 = new HashMap<Book, LocalDateTime>();
public Library(String person, LocalDateTime time)
{
try{
File myfile = new File("input1.txt") ;
Scanner br = new Scanner(myfile);
String line = br.nextLine();
while ((line != null))
{
String a = line;
line = br.nextLine();
String b = line;
Book a1 = new Book(a,b,person);
Book a2 = new Book (a,b, "");
var.add(a2);
var1.put(a1,time);
//System.out.println(a + " "+ b);
line = br.nextLine();
}
br.close();
}
catch (Exception e)
{
System.out.println("not working");
}
}
}
with code:
public class Main{
public static void main(String[] args) {
int counter = 0;
try (FileReader fileReader = new FileReader("src/file.txt"); Scanner sc = new Scanner(fileReader)) {
while (sc.hasNextLine()) {
++counter;
sc.nextLine();
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage());
}
System.out.println(counter);
}
}
checkout: how to read file in Java
I have this code set up and I am trying to write a program that looks through a file and finds a specific hidden secret word then replaces the word with "found!" then re-prints the text file in the console. I know how to use reader and writer but I am unsure how i can use them in unison to do this. Code is as follows:
Reader Class:
package Main;
import java.io.*;
public class Read {
private static String line;
FileReader in;
File file;
public Read() {
line = "";
}
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
}
public String getLine() {
return line;
}
public File getFile() {
return file;
}
}
Writer(change) class:
package Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Change {
public static void main(String[] args) throws IOException{
Read r = new Read();
String line = r.getLine();
FileWriter fw = new FileWriter(r.getFile());
while(line != null) {
if(line.equals("example")) {
fw.write("found!");
}
System.out.println(line);
}
}
}
Am i on the right path or should i combine both of these into one class. Also is this the proper way of writing to a specific line in a text file?
If the file is a reasonable size, you can read it into memory, change what you need and write it back out again:
public static void replaceOccurrences(String match, String replacement, Path path) throws IOException {
Files.write(path, Files.lines(path).map(l -> {
if(l.contains(match)) {
return l.replace(match, replacement);
} else {
return l;
}
}).collect(Collectors.toList()));
}
Alternatively, if you know that the search term occurs only once and you just need to find the position of the occurrence, use the following:
try(BufferedReader reader = Files.newBufferedReader(path)) {
int lineIndex = 0;
String line;
while(!(line = reader.readLine()).contains(match)) {
lineIndex++;
}
System.out.println(lineIndex); // line which contains match, 0-indexed
System.out.println(line.indexOf(match)); // starting position of match in line, 0-indexed
}
If all you have to do is print the converted text to system out (rather than writing it out to a file), the second class isn't really needed. You can accomplish what you need in the readFile() method of the Read class:
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line.replaceAll("example", "found!"));
}
in.close();
}
There are a lot of other tweaks you could make, but that's the core of the functionality you specified in your question.
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?
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.
I am consider a rookie and I have searched for hours on the internet to solve my problem but still no luck.
I really want to understand java and if you could explain some detail that will be highly grateful.
The problem is in this line
ReadFile file = ReadFile(file_name);
error message : "ReadFile cannot be resolved to a type."
Here is my code: FileData.java
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "D:/java/readfile/test.txt";
try {
ReadFile file = ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i =0; i < aryLines.length ; i++) {
System.out.println( aryLines[i] );
}
}
catch (IOException e) {
System.out.println( e.getMessage() );
}
}
}
And this is my other code: ReadFile.java
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile (String file_path) {
path = file_path;
}
int readLines () throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine() ) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile () throws IOException {
FileReader fr = new FileReader (path);
BufferedReader textReader = new BufferedReader (fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] =textReader.readLine();
}
textReader.close();
return textData;
}
}
Try this:
ReadFile file = new ReadFile(file_name);
In order to initialize an object with it's class name you should use the new key word like this:
ClassName objName = new ClassName(arguments);
From the rest of your code seems you know the notion, nevertheless I refer you (or possible future visitors) to this page.