Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am very new to Java and I am working on a project. I have been told that in order to complete this project I will need to save a file into a hash map. This file contains words and their abbreviation so later on I want to be able to search for a particular word and then return the abbreviation for it. I have been able to make the hash map and access the file, but I'm stuck on how to save it into the hash map.
public Shortener() {
Map<String, String> abbrevFile = new HashMap<String, String>();
File file = new File("C:\\abbreviations.txt");
I would use a properties file as it's an existing format.
e.g.
Hello=Hi
Abreviation=Abr
such as
Properties p = new Properties();
p.load(file);
abbrevFile.putAll((Map) p);
To look up the map you can do
public String lookup(String word) {
return abbrevFile.get(word);
}
Here is an example of reading a file and storing the data in the hashmap
static HashMap<String, String> wordList = new HashMap<>();
public static void main(String[] args) {
readFile(new File("words.txt"));
}
private static void readFile(File file) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split("-");
wordList.put(args[0], args[1]);
}
System.out.println("Populated list with "+ wordList.size() + " words.");
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Providing your format is in the following format
word-abbreviation
word-abbreviation
word-abbreviation
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to be able to go through a folder containing files and display the files that have been specified. I currently have it hard coded... Cc
public void searchResult(String a) throws IOException {
FileReader inputFile;
a = "C:\\IO\\Project.txt";
try {
inputFile = new FileReader(a);
BufferedReader br = new BufferedReader(inputFile);
while ((str = br.readLine()) != null) {
searchResult.setText(str);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(SearchResults.class.getName()).log(Level.SEVERE, null, ex);
}
}
Please, I need something more dynamic.
i currently have it hard coded
Do you understand how passing parameters work?
public void searchResult(String a) throws IOException
{
a = "C:\\IO\\Project.txt";
try {
inputFile = new FileReader(a);
What is the point of hardcoding the value of "a". The point of using parameters is to pass the file name as a parameter to you method.
So the code should simply be:
public void searchResult(String a) throws IOException
{
try {
inputFile = new FileReader(a);
Also the following makes no sense:
while ((str = br.readLine()) != null) {
searchResult.setText(str);
Every time you read a new line of text you replace the previous line of text. You need to append(...) the text.
Or, the better solution is to just use the read(...) method of the JTextArea to load data from the file.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm making a launcher for my game using Java Swing. I need a way to add a tumblr/wordpress feed onto the launcher. An example would be the minecraft launcher (If you don't know what it looks like, go to this link).
I was also thinking RSS could be useful because I've seen that mentioned on feeds and stuff like this so if there's a simple way with that then that'd be helpful too.
Anyway, how would I do this?
EDIT: How would I use jsoup in Swing?
Here's an example I have used to parse data from a page
private static final String url = "website";
public void getLatestUpdate() throws IOException {
try {
URL addr = new URL(url);
URLConnection con = addr.openConnection();
ArrayList<String> data = new ArrayList<String>();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Pattern p = Pattern.compile("<span itemprop=.*?</span>");
Pattern p2 = Pattern.compile(">.*?<");
Matcher m = p.matcher(inputLine);
Matcher m2;
while (m.find()) {
m2 = p2.matcher(m.group());
while (m2.find()) {
data.add(m2.group().replaceAll("<", "").replaceAll(">", "").replaceAll("&", "").replaceAll("#", "").replaceAll(";", "").replaceAll("3", "3"));
}
}
}
in.close();
addr = null;
con = null;
message("(" + data.get(3) + ")" + ", at " + data.get(4));
} catch (Exception e) {
System.out.println("Error getting data from website.");
e.printStackTrace();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
is there any simple way (in Java 7) to:
open in reading mode a file containing, for every line, a path to another file
for every line/path, open the respective file and print the content
(Every file is a plain text file)
?
Sorry if the question is silly.
Thank you
try something like this:
public static void main(String[] args) throws IOException {
// open stream to path list file
InputStream indexSource = new FileInputStream("index.txt");
// create reader to read content
try(BufferedReader stream = new BufferedReader(new InputStreamReader(indexSource))) {
// loop
while (true) {
// read line
String line = stream.readLine();
if (line == null) {
// stream reached end, escape the loop
break;
}
// use `line`
printFile(line);
}
}
}
static void printFile(String path) throws IOException {
// open stream to text file
InputStream textSource = new FileInputStream(path);
// print file path
System.out.println("### " + path + " ###");
// create reader to read content
try(BufferedReader stream = new BufferedReader(new InputStreamReader(textSource))) {
// loop
while (true) {
// read line
String line = stream.readLine();
if (line == null) {
// stream reached end, escape the loop
break;
}
// print current line
System.out.println(line);
}
}
// nicer formatting
System.out.println();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have two files, File1.txt and File2.txt. Both files contain texts. I want to know the total number of common words present in these files. I have got the total number of words in each file by using this code.
public int get_Total_Number_Of_Words(File file) {
try {
Scanner sc = new Scanner(new FileInputStream(file));
int count = 0;
while (sc.hasNext()) {
sc.next();
count++;
}
return count;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
Kindly tell me how can i use this code to count the common words between two files.
Use a Map implementation. Take the word as the key, Integer as the value that you increment whenever you found the key. Voila!
public static void main(String[] args) {
String[] wordList = new String[]{"test1","test2","test1","test3","test1", "test2", "test4"};
Map<String, Integer> countMap = new HashMap<String, Integer>();
for (String word : wordList) {
if (countMap.get(word)==null) {
countMap.put(word, 1);
}
else {
countMap.put(word, countMap.get(word)+1);
}
}
System.out.println(countMap);
}
Result is:
{test4=1, test2=2, test3=1, test1=3}
Here is a solution using Java 8 and a project of mine:
private static final Pattern WORDS = Pattern.compile("\\s+");
final LargeTextFactory factory = LargeTextFactory.defaultFactory();
final Path file1 = Paths.get("pathtofirstfile");
final Path file2 = Paths.get("pathtosecondfile");
final List<String> commonWords;
try (
final LargeText t1 = factory.fromPath(file1);
final LargeText t2 = factory.fromPath(file2);
) {
final Set<String> seen = new HashSet<>();
final Stream<String> all
= Stream.concat(WORDS.splitAsStream(t1), WORDS.splitAsStream(t2));
commonWords = all.filter(s -> { return !seen.add(s); })
.collect(Collectors.toList());
}
// commonWords contains what you want
It could be parallelized if you chose to use a concurrent implementation of Set, too.
You have to have some kind of comparison. So you can use a nested loop to do it.
String word1, word2;
int numCommon = 0;
try {
Scanner sc = new Scanner(new FileInputStream(file));
Scanner sc2 = new Scanner(new FileInputStream(file2));
while (sc.hasNext()) {
word1 = sc.next();
while(sc2.hasNext()){
word2 = sc2.next();
if(word2.equals(word1))
numCommon++;
}
}
return numCommon;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
I would create 2 list and add the words from one textfile to one list and add the words from the other text file to the other list, then compare the two and count the words that are the same.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to know if it's possible to do this:
i've some .txt file in a directory in my filesystem
i would like to write a java code that does this:
Automatically read all the files in the directory
Give me a output
Exists some library? or it's just a code problem?
It's possible?
Thanks
Reads & prints the content
public static void main(String[] args) {
List<String> li=new TestClass().textFiles("your Directory");
for(String s:li){
try(BufferedReader br = new BufferedReader(new FileReader(s))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.println(everything);
} catch (IOException e) {
e.printStackTrace();
}
}
}
For getting all Text files in the Directory
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getPath());
}
}
return textFiles;
}
Of course it's possible. You need to look at File, Reader classes. A useful method is File#listFiles. Happy coding.