Need a word list from the internet - java

Hello I'm creating a HangMan game and I want the array list of words to come from the internet. Its not initializing for me. Can anyone help? This is the code.
public String getaword()
{
try
{
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt");
//URLConnection urlConnection = (URLConnection)url.openConnection();
//inStream = new InputStreamReader(urlConnection.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null)
{
lines.add(str);
words = lines.toArray(new String[lines.size()]);
}
}
catch (Exception e)
{
e.getStackTrace();
}
Random r = new Random();
int num;
num = r.nextInt(words.length);
return words[num];
}

Try this.
public static void main(String[] args) {
ArrayList<String> lines = new ArrayList<String>();
try {
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives(929).txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
while((str = in.readLine()) != null) {
lines.add(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(lines);
}

Related

Get range of lines in file

i would like to save in a string multiple lines from reading file, eg: I am reading one file.txt with the following content:
def var x as int.
def var y as char.
procedure something:
//here some content
end.
I would like to catch content between "procedure" and "end".
public static void main(String[] args) {
String piContent = "";
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.contains("procedure")){
piContent = line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I appreciate any help.
final StringBuilder sb = new StringBuilder();
try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
boolean rememberStuff = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("procedure ")) {
rememberStuff = true;
} else if (line.startsWith("end.")) {
rememberStuff = false;
} else if (rememberStuff) {
sb.append(line).append('\n');
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("Lines found between procedure and end:");
System.err.println(sb);
public static String getContentFromFile(Path file) throws IOException {
StringBuilder buf = new StringBuilder();
boolean add = false;
for (String line : Files.readAllLines(file)) {
if ("end.".equalsIgnoreCase(line.trim()))
break;
if (add)
buf.append(line).append(System.lineSeparator());
else if ("procedure something:".equalsIgnoreCase(line.trim()))
add = true;
}
return buf.toString();
}

Comparing two file contents in java and save it another file

this is my code, im trying to compare two .csv files and match them and save the common pain in another file. How do i do it?
This is the cotnent of item_no.csv file
1
2
3
4
5
This is the content of item_desc.csv file
1,chocolate,100
2,biscuit,20
3,candy,10
4,lollipop,5
5,colddrink,50
6,sandwitch,70
EDIT This is the expected output:
1,chocolate,100
2,biscuit,20
3,candy,10
4,lollipop,5
5,colddrink,50
This is my code:
package fuu;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class Demo {
public static void main(String[] args) throws ParseException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new FileReader("/home/yotta/eclipse/workspace/Test/WebContent/doc/item_no.csv"));
BufferedReader br1 = new BufferedReader(new FileReader("/home/yotta/eclipse/workspace/Test/WebContent/doc/item_desc.csv"));
String line = null;
String line1 = null;
String line2 = null;
String[] str=null;
String[] str1=null;
try {
while((line = br.readLine())!=null){
str = line.split(",");
System.out.println(str[0]);
}
while((line1 = br1.readLine())!=null){
str1 = line1.split(",");
System.out.println(str1[0]+" "+str1[1]+" "+str1[2]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You could separate the different steps.
public class Demo {
public static void main(String[] args) throws IOException {
Map<String, String> descMap = new HashMap<>();
String line;
// read all item descriptions
try (BufferedReader br1 = new BufferedReader(new FileReader("item_desc.csv"))) {
while ((line = br1.readLine()) != null) {
int itemNbrSeparator = line.indexOf(',');
String itemNbr = line.substring(0, itemNbrSeparator);
descMap.put(itemNbr, line);
}
}
List<String> matched = new ArrayList<>();
// read the item numbers and store each matched
try (BufferedReader br = new BufferedReader(new FileReader("item_no.csv"))) {
while ((line = br.readLine()) != null) {
if (descMap.containsKey(line)) {
System.out.println(descMap.get(line));
matched.add(descMap.get(line));
}
}
}
// output all matched
Path outFile = Paths.get("item_match.csv");
Files.write(outFile, matched, Charset.defaultCharset(), new LinkOption[0]);
}
}
One way is this
List<String> lines1 = new ArrayList<String>();
while ((line = br.readLine()) != null) {
str = line.split(",");
lines1.add(line);
System.out.println(str[0]);
}
List<String> lines2 = new ArrayList<String>();
while ((line = br1.readLine()) != null) {
str = line.split(",");
System.out.println(str[0]);
if(lines1.contains(str[0])){
lines2.add(line);
}
}
for (String l : lines1) {
System.out.println(l);
}

How to open a txt file located on the web and read its contents to a string?

I have looked around on how to do this and I keep finding different solutions, none of which has worked fine for me and I don't understand why. Does FileReader only work for local files? I tried a combination of scripts found on the site and it still doesn't quite work, it just throws an exception and leaves me with ERROR for the variable content. Here's the code I've been using unsuccessfully:
public String downloadfile(String link){
String content = "";
try {
URL url = new URL(link);
URLConnection conexion = url.openConnection();
conexion.connect();
InputStream is = url.openStream();
BufferedReader br = new BufferedReader( new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
content = sb.toString();
br.close();
is.close();
} catch (Exception e) {
content = "ERROR";
Log.e("ERROR DOWNLOADING",
"File not Found" + e.getMessage());
}
return content;
}
Use this as a downloader(provide a path to save your file(along with the extension) and the exact link of the text file)
public static void downloader(String fileName, String url) throws IOException {
File file = new File(fileName);
url = url.replace(" ", "%20");
URL website = new URL(url);
if (file.exists()) {
file.delete();
}
if (!file.exists()) {
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
}
Then call this function to read the text file
public static String[] read(String fileName) {
String result[] = null;
Vector v = new Vector(10, 2);
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String tmp = "";
while ((tmp = br.readLine()) != null) {
v.add(tmp);
}
Iterator i = v.iterator();
result = new String[v.toArray().length];
int count = 0;
while (i.hasNext()) {
result[count++] = i.next().toString();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return (result);
}
And then finally the main method
public static void main(){
downloader("D:\\file.txt","http://www.abcd.com/textFile.txt");
String data[]=read("D:\\file.txt");
}
try this:
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder();
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
sb.append(str );
}
in.close();
String serverTextAsString = sb.toString();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

Public string - cannot be resolved

Error at
bw.write(dataString);
How can i fix this?
dataString cannot be resolved to a variable.
public class test {
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
String dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
DeclaredataString outside of the try and catch block... Thats all. ;) If you declare it inside a loop or in this case your try catch block, its lifecycle is limited to it.
Like this:
String dataString = null;
and inside the try-catch block:
dataString = Arrays.toString(dataArray);
dataString is out of scope in the try block.
Perhaps add dataString as an instance variable at the top of your class.
public class test {
private String dataString = null;
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
...
The dataString variable's scope is limited to the first try-catch block. Change its declaration as following,
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
String dataString = null;
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Bufferedreader returning null

i'm trying to read a web address from a text and then have the app open that address, my buffered reader seems to be reading the lines correctly but readline keeps coming back null
String rsslink = null;
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rsslink = br.readLine()) != null)
{
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
You will get the last line that is null rsslink.
You need to change your loop
try {
while ((rsslink = br.readLine()) != null)
{
}
}
to
try {
StringBuilder sb= new StringBuilder();
while ((rsslink = br.readLine()) != null)
{
sb.append(rsslink);
}
rsslink = sb.toString();
}
Use this:
String rsslink = "";
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink +=line ;
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink;
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
Better your StringBuffer orStringBuilder.
StringBuilder rsslink = new StringBuilder();
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
while ((line = br.readLine()) != null)
{
rsslink.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
String RSS_LINK = rsslink.toString();

Categories

Resources