im trying to put all stopwords on a hashset, i dont want to add it one by one so im trying to put in a txt file and have my scanner scan it. the problem is i think my code does not reach my scanner here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class StopWords {
public static final Set<String> stopWords = new HashSet<String>();
private static class scan {
public scan()throws IOException {
Scanner s = null;
try{
s = new Scanner(new BufferedReader(new FileReader("stopwords.txt")));
while (s.hasNext()) {
//System.out.println(s.next());
stopWords.add(s.next());
}
}finally{
if (s != null) {
s.close();
}
}
}
}
}
im running my main on other class and im just calling this class. thanks in advance
Make a wrapper for it in enclosing class.
Something like:
public void doScan() {
try {
scan.scan();
catch (IOException e) {};
}
in StopWords class.
This way you could call doScan() on instance of StopWords. You could also make it static.
And I agree that you should follow naming convections of Java language (wikipedia.org).
Just want to add a couple tricks you might consider:
First - you could store your stopwords in a properties file, then use java.util.Properties.load to pull the data in.
Second - you can put your stopwords file on your classpath, and bundle up the stopwords file with the rest of your code in a jar for delivery.
You wind up with something like this:
final Properties stopProps = new java.util.Properties();
stopProps.load( new InputStreamReader( this.class.getClassLoader().getResourceAsStream( "mycode/stopWords.properties", "UTF-8" ) );
...
Good luck!
Related
I want to have a setting system that I can read write and use variables from the are stored in a file.
To summarize, There is a class and inside that class is a list of settings.
When I make a setting I want to add it to the list so that I can write it to the text file later.
I also want to be able to get the setting value without casting it which would use generics.
So for boolSetting I would only need to do boolSetting.get() or boolSetting.value ect
To start with code I have already written I have the code to read and write to the file. This works perfect (I think). I just need help with the setting part. Here is the read and write to file.
package winter.settings;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import net.minecraft.src.Config;
import winter.Client;
public class WinterSettings {
public static File WinterSetting;
public static void readSettings() {
try {
File WinterSetting = new File(System.getProperty("user.dir"), "WinterSettings.txt");
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream(WinterSetting), "UTF-8"));
String s = "";
while ((s = bufferedreader.readLine()) != null)
{
System.out.println(s);
String[] astring = s.split(":");
Client.modules.forEach(m ->{
if(m.name==astring[0]) {
m.settings.forEach(setting ->{
if(setting.name==astring[1]) {
setting.value=astring[2];
}
});
}
});
}
bufferedreader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeSettings() {
try {
File WinterSetting = new File(System.getProperty("user.dir"), "WinterSettings.txt");
PrintWriter printwriter = new PrintWriter(new FileWriter(WinterSetting));
Client.modules.forEach(m ->{
m.settings.forEach(setting ->{
printwriter.println(m.name+":"+setting.name+":"+setting.value);
});
});
printwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Pretty much how this works is I have a setting in a Module which just stores some information.
The setting has a name and a value
To write it I am just writing
The module name, the setting name, the setting value For example: ModuleName:SettingName:false
This works fine, but leads to the problem that I just don't know enough about generics. I can't find a way that works with writing reading and setting / getting. The setting should have a name and value. Some code I wrote is below I just don't know how to continue it.
public class Setting<T> {
public String name;
public T value;
public Setting(String name, T value) {
this.name = name;
this.value = value;
}
public T getValue() {
return value;
}
}
From here I have subclasses for each type of setting. Not sure if this is good programming or not.
Now I can set get / write, but when I read the value isn't updated correctly.
Right now I make a new setting like
private final BooleanSetting toggleSprint = new BooleanSetting("ToggleSprint", true);
There is one problem to this from what I can tell. First off when I try to add it to a list when initilizing I get an error.
Type mismatch: cannot convert from boolean to BooleanSetting.
In short: I need to be able to read write get and set a value in a setting object. This can be boolean / int / ect.
Above is some of my code to read / write to txt file. Setting class and what I have of making a new setting.
My 2 problems are that I read the settings correctly and when making them I can't add them to a list.
Use the Boolean.True static variable
new BooleanSetting("ToggleSprint", Boolean.TRUE);
or
Boolean.valueOf(true)
I am trying to read file from classpath in a reactive way using spring webflux. I am able to read the file. But I am not able to parse into an Foo object.
I am trying the following way, but not sure how to convert to an FOO class.
public Flux<Object> readFile() {
Flux<DataBuffer> readFile1 = DataBufferUtils.read("classpath:test.json", new DefaultDataBufferFactory(), 4096);
return new Jackson2JsonDecoder().decode(readFile1,
ResolvableType.forType(List.class,Foo.class), null, Collections.emptyMap());
}
Help appreciated.
I think you are doing it correctly but you unfortunately must cast the Object back into the correct type. This is safe to do because the JSON decoding will fail if it was unable to construct a list of Foo:
public Flux<Foo> readFile() {
ResolvableType type = ResolvableType.forType(List.class,Foo.class);
Flux<DataBuffer> data = DataBufferUtils.read("classpath:test.json", new DefaultDataBufferFactory(), 4096);
return new Jackson2JsonDecoder().decode(data, type, null, null)
.map(Foo.class::cast);
}
You can use jackson ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue(jsonString, Student.class);
And before that, you should read the file and use FileReader and readLines() to parse line by line.
[UPDATE]
Ok, for reading file, reactive means, reading file in a stream, and whenever a line is read, process this line. From this point, the BufferReader.readLines will be fine. But if you really want to use reactive way, you can use:
package com.test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class TestReadFile {
public static void main(String args[]) {
String fileName = "c://lines.txt";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(parseLine);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have been trying to execute this program, but it shows error saying that urlconnectionreader cannot be resolved. I'm new to programming. Can someone help me with this?
This is my code:
import java.net.*;
import java.io.*;
public class ReadTextFromUrl {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
// enter code here
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
There are Many Libraries to read text from URL,
You can Try jsoup library to read or extract only text.
import java.io.IOException;
import org.jsoup.Jsoup;
public class ReadTextFromURL {
public static void main(String[] args) throws IOException {
String text = Jsoup.connect("https://stackoverflow.com/questions/40741265/read-only-text-from-url-using-java").get().text();
System.out.println(text);
}
}
In your case the class name should be URLConnectionReader or you can change the the calling function via your class name .
String content = ReadTextFromUrl.getText(args[0]);
what you need to study more is objects.you must know that the classes are the blueprints.you cant use a saw blueprint to saw a tree.you need the saw itself.and by creating a object from that class you will have the saw.so when you have the saw in your hands you can saw the tree.making an object from a class works exactly the same.and using the ways(methods) to saw the tree with the actual saw is like using the methods of the class.
lets think you have a class named Saw and it has a method named sawTheTree.
public class Saw {
public void sawTheTree {
// do the sawing
}
}
its the blueprint by now.to use this saw and the method you need this :
Saw saw = new Saw();
now you have the saw in your hands.lets go and saw the tree.for this you need this code in your main method or where ever you feel the need of sawing the tree.
saw.sawTheTree();
now the the saw will saw the tree for you.
P.S: in your code you have declared the getText method static so you don't need the object creation part.if you are asking why look again at static statement description.but to use a non static method from a class you need to create the object.
So here is a code I wanted to test..(This is for understanding how to convert to CSV file)
String csv = "C:\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
String [] country = "India#China#United States".split("#");
writer.writeNext(country);
writer.close();
Here is the class I imported , import au.com.bytecode.opencsv.CSVWriter; , I made sure the path is built.
Im trying out that code so I can understand its working but its confusing me now.
ANY sort of help is appreciated.
I know there are so many similar questions, I did have read through some and got confused.
I am getting CSVWrite cannot be resolved to type.
Here is my ENTIRE code:
I am learning how to take content off web and convert it into a csv file.
import java.net.*;
import java.io.*;
import au.com.bytecode.opencsv.CSVWriter;
public class InfoGather {
private static BufferedWriter out;
/*private static String csv;
private static BufferedReader csvin;*/
public static void main(String[] args) throws IOException {
try{
URL blog = new URL("http://protectidentite.blogspot.ca/2014/02/mobile-phones-are-one-of-most-popular.html");
URLConnection connect= blog.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
FileWriter fstream = new FileWriter("out.txt");
out = new BufferedWriter(fstream);
String inputLine;
while((inputLine = in.readLine())!= null)
{
out.write(inputLine);
out.newLine();
}
/* csv = "C:\\output.csv";
csvin = new BufferedReader(new FileReader("out.txt")); */
String csv = "C:\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
String [] country = "India#China#United States".split("#");
writer.writeNext(country);
writer.close();
}
catch(IOException e)
{
System.out.println("error");
}
}
}
Majority of it is taken from the web. I also created another class which generates an excel file.
Looks like you don't have clear understanding about import statement. Basically there are Java's own libraries means many many jars containing many many classes, by default, only those are accessible to JVM. So using import we can contact with any class that is inside those jars.
If you want to use a class that is not from default java libraries you need to add the jar that contains that class and after jvm is able to contact that class then you need to import that class by import a.b.c.d.CSVWriter.
Make sense?
I want to read text and STORE it in a String variable ...
This code is working fine but i want to know where the txt file should be placed exactly for me to not specify the exact path. Since I'll be trying this code on various machines . so I hope you understood what I want.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Compress {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String text="";
try {
text = new Scanner( new File("C:\\Users\\sandhya\\workspace\\PrefixFreeCodeChecker\\src\\poem.txt"), "UTF-8" ).useDelimiter("\\A").next();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(text+"");
}
}
Put your poem.txt file in your java project folder and change the path to this:
text = new Scanner( new File("poem.txt").....