I have a TXT file like this:
Start: Here is a random introduction.
Items:
Item 1
Item 2
Item 3
Item 4
End: Here is a random outro.
I want to retrieve Item 1, Item 2, Item 3, Item 4 and put them into a data structure like a HashMap. How can I achieve this?
Here is what I've tried so far:
public static void main(String[] args) {
Scanner scanner = null;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("Start:")) {
String time = line.substring(6);
}
if (line.matches("Items:") && scanner.hasNextLine()) {
String items = line;
}
}
}
[Updated Answer] So the other answer on this question is helpful if the exact words are know that are to be ignored but when there is a big file with lot of lines than this solution will be more accurate.
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "";
String[] parts = null;
HashMap<String, String> hashmap=new HashMap<String, String>();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
//line = br.readLine();
while (line != null) {
line = br.readLine();
//System.out.println(line.toString());
if(line!=null){
//System.out.println(line);
if(line.contains("Item")&& line.substring(0, 5).compareTo("Item ")==0){
addToHashMap(line,hashmap);
System.out.println(line);
}
}
}
br.close();
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}
}
private static void addToHashMap(String line, HashMap<String,String> hashMap) {
// TODO Auto-generated method stub
Random random=new Random();
hashMap.put(Integer.toString(random.nextInt(100)), line);
}
The following code should work:
public static void main(String[] args) {
Scanner scanner = new Scanner(TestCdllLogger.class.getResourceAsStream("/test.txt"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("Start:") || line.startsWith("End:") || line.startsWith("Items:") || line.startsWith(" ") ||line.isEmpty() ) {
continue;
}
System.out.println(line);
}
}
it ignores all lines starts with Start:, End:, Items: and blank or emty lines.
I know that the code write the lines to stdout and not to a file, but this can changed by your own
Related
I am reading a file in java which has .lab extension which is basically a text file with utf characters and has content as follows:
0.100904 125 SIL
0.392625 125 तुझ्_beg
0.622405 125 या_end
0.623404 125 SIL
0.946096 125 ले_beg
1.120000 125 मळ्_mid
1.362698 125 या_end
1.363697 125 SIL
but in program when i compare as follows:
arr[2].equals("SIL")
it doesn't work.
entire java code is as follows:
public class SyllableCount
{
static final File labDir = new File("/media/sda6/tts/programs/MyWork/silence_handling/labs_4");
static final HashMap<String, ArrayList<Float>> terminalSyllMap = new HashMap<String, ArrayList<Float>> ();
public void accessFilesForFolder(final File labDir)
{
System.out.println("in method");
for (final File labFile : labDir.listFiles())
{
if (labFile.isDirectory())
{
accessFilesForFolder(labFile); //for recursive operation
} else
{
System.out.println(labFile.getName());
BufferedReader br = null;
String[] syllable = new String[100];//just an example-you have to initialize it big enough to hold all lines
float[] timeFrame = new float [100];
String sCurrentLine;
try
{
//br = new BufferedReader(new FileReader(labFile));
br = new BufferedReader(new InputStreamReader(new FileInputStream(labFile), "UTF8"));
int lineNo=0;
while ((sCurrentLine = br.readLine()) != null)
{
String[] arr = sCurrentLine.split(" ");
//for the first line it'll print
if(arr[0].equalsIgnoreCase("#"))
{
lineNo++;
continue;
}
//entering them into separate arrays
timeFrame[lineNo] = Float.parseFloat(arr[0]);
syllable[lineNo] = arr[2];
lineNo++;
}
br.close();
populateMaps(timeFrame, syllable, lineNo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(terminalSyllMap);
}
public void populateMaps(float[] timeFrame,String[] syllable, int lineNo) throws Exception
{
String syllval;
float duration;
ArrayList<Float> timeframeArray;
for(int i=0; i<lineNo-1; i++)
{
//System.out.println(syllable[i+1]);
if (syllable[i+1].equals("SIL"))
{
syllval = syllable[i];
duration = timeFrame[i+1] - timeFrame[i];
if(terminalSyllMap.containsKey(syllval))
{
timeframeArray = terminalSyllMap.get(syllval);
}
else
{
timeframeArray = new ArrayList<Float>();
}
timeframeArray.add(duration);
terminalSyllMap.put(syllval, timeframeArray);
}
}
}
public static void main(String[] args)
{
//
SyllableCount run = new SyllableCount();
run.accessFilesForFolder(labDir);
}
}
any help would be highly appreciated.
Try with:
final String[] arr = sCurrentLine.split("\\s+");
I have almost managed to accomplish this but not to the full. So what I need is for example I give the word DOG and the program will look into a text file and return DOG and GOD, i.e words that can be generated by the odds given only. My code is giving me all words that contain 'D', 'O' and 'G'. My code is this:
public class JavaReadTextFile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ReadFile rf = new ReadFile();
String filename = "/Users/Elton/Desktop/OSWI.txt";
String wordinput;
String wordarray[] = new String[1];
System.out.println("Input Characters: ");
wordinput = input.nextLine();
wordarray[0] = wordinput;
System.out.println(wordinput.length());
try {
String[] lines = rf.readLines(filename);
for (String line : lines) {
if (line.matches(wordarray[0] + ".*")) {
System.out.println(line);
}
}
} catch (IOException e) {
System.out.println("Unable to create " + filename + ": " + e.getMessage());
}
}
}
----- then i have:
public class ReadFile {
String [] cName = new String [100];
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null ) {
cName[0] = line.split(" ")[0];
lines.add(cName[0]);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
I can see you are able to read the words from file. Rest of the work is simple. algorithm will be something like this
sort inputWord
sort the word you read from file
if both word is same print or add it to some list.
And here is simple demonstration of above algorithm you can modify it to your need.
public class App {
static String sortString (String str) {
char []chars = str.toCharArray();
sort(chars);
return new String(chars);
}
public static void main(String... args) {
String inputWord = "DoG";
String readWord = "God";
inputWord = inputWord.toUpperCase();
readWord = readWord.toUpperCase();
inputWord = sortString(inputWord);
readWord = sortString(readWord);
if(inputWord.equalsIgnoreCase(readWord)) {
System.out.println(readWord);// you can add it to your list
}
}
}
If I understand you correctly, you want to display all the anagrams of a word?
Change your method readLines() to return an ArrayList instead of an array.
ArrayList<String> readLines(String fname) {
File file = new File(fname);
ArrayList<String> list = null;
try {
Scanner scanner = new Scanner(file);
list = new ArrayList<String>();
while (scanner.hasNext()) {
String currentWord = scanner.next();
if (!currentWord.isEmpty()) {
list.add(currentWord);
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
The use this function with input parameter dictionary being the ArrayList you return from readLines. The function uses the fact that two anagrams like "DOG" and "GOD" are equal strings when both are sorted (i.e. "DGO" equals "DGO")
public ArrayList<String> getAnagrams(String word, ArrayList<String> dictionary) {
if(word == null || dictionary == null) {
return null;
}
ArrayList<String> anagrams = new ArrayList<String>();
char[] sortedChars = word.toCharArray();
Arrays.sort(sortedChars);
for(String item : dictionary) {
char[] sortedDictionaryItem = item.toCharArray();
Arrays.sort(sortedDictionaryItem);
if(Arrays.equals(sortedChars, sortedDictionaryItem)) {
anagrams.add(item);
}
}
return anagrams;
}
If you don't like the changes I am suggesting, you can also do the following. In the loop where you do:
if (line.matches(wordarray[0] + ".*")) {
System.out.println(line);
}
You can check if the two strings are permutations of each other:
if (isPermutation(line, wordarray[0]) {
System.out.println(line);
}
By adding these two functions:
String sortString(String s) {
char[] chars = s.toCharArray();
java.util.Arrays.sort(chars);
return new String(chars);
}
boolean isPermutation(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
s1 = sortString(s1);
s2 = sortString(s2);
return (s1.compareTo(s2) == 0);
}
This may help you adapt your code.
import java.util.regex.* ;
public class Find_Dogs_And_Gods
{
public static void main(String []args)
{
String line = "2ldoghmDoggod" ;
Pattern p = Pattern.compile("[d,D,g,G][o,O][d,D,g,G]") ;
Matcher m = p.matcher(line) ;
while(m.find() )
{
System.out.println( m.group() ) ;
}
}
}
I want to read a text file and print the word previous to known word say xxx for instance in Java.
Ive written this code in java using Scanner class.
but this code prints only half of the word preceding to "xxx" some other words preceding "xxx" are missing.
I want to know whats the problem and can u troubleshoot this code.
Test file contains stuff like
Blah blah blah.. man xxx create blah blah .. wander xxx blah... then xxx ..
Need to print man,wander,then etc.,
public class Searchright {
public static void main(String[] args) throws IOException {
Scanner s = null;
String str;
try {
s = new Scanner(new BufferedReader(new FileReader("doc.txt")));
str=s.next();
do{
//while (s.hasNext()) {
str=s.next();
if((s.hasNext(("xxx"))||s.hasNext(("X.X.X”))))
{
//System.out.println(s.next()+" "+s.next() );
//System.out.println(s.next());
System.out.println(str);
//s.next();
}
s.next();
//System.out.println(s.next());
}while(s.hasNext());
}
finally{
if (s != null) {
//s.close();
}
}
}
}
public class Searchright {
public static void main(String[] args) throws IOException {
Scanner s = null;
String str;
try {
s = new Scanner(new BufferedReader(new FileReader("doc.txt")));
do{
//while (s.hasNext()) {
str=s.next();
if((s.hasNext(("xxx"))||s.hasNext(("X.X.X”))))
{
//System.out.println(s.next()+" "+s.next() );
//System.out.println(s.next());
System.out.println(str);
//s.next();
}
//System.out.println(s.next());
}while(s.hasNext());
}
finally{
if (s != null) {
//s.close();
}
}
}
}
remove s.next() before do loop and before while block inside do loop.
It escape words two times in one loop.Thus causing missing word.
Your code already prints man and wander though then is missing. I've updated your code a bit to use try with resources instead of try-finally and assigned the next word to a own variable which is tested for the required string:
public static void main(String[] args) throws IOException
{
try (Scanner s = new Scanner(new BufferedReader(new FileReader("doc.txt"))))
{
String str=s.next();
String next;
do
{
next = s.next();
if( next.equals("xxx") || next.equals("X.X.X") )
{
// Need to print man,wander,then etc.,
System.out.println(str);
}
str = next;
}
while(s.hasNext());
}
}
HTH
The problem is just a simple one: you call Scanner.next 2 times in the loop instead of 1 time: This should work:
public class Searchright {
public static void main(String[] args) throws IOException {
Scanner s = null;
String str;
try {
s = new Scanner(new BufferedReader(new FileReader("doc.txt")));
str=s.next();
do{
//while (s.hasNext()) {
str=s.next();
if((s.hasNext(("xxx"))||s.hasNext(("X.X.X”))))
{
//System.out.println(s.next()+" "+s.next() );
//System.out.println(s.next());
System.out.println(str);
//s.next();
}
//-> ADDED COMMENT HERE -------------------------- s.next();
//System.out.println(s.next());
}while(s.hasNext());
}
finally{
if (s != null) {
//s.close();
}
}
}
}
I thought that the code should be as similar as the one in the question. It really just adds the comment that starts with "//-> ADDED COMMENT HERE"
I have create the following program and I am little stuck here.
Here is the code:
class ProductNameQuan{
public static void main(String[] args)
{
String fileName = "stockhouse.txt";
StringTokenizer line;
String ProdName;
String quantity;
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
while (line != null) {
ProdName = line.nextToken();
quantity = line.nextToken();
System.out.println(line);
line = in.readLine();
}
in.close();
} catch (IOException iox)
{
System.out.println("Problem reading " + fileName);
}
}
}
I am trying to find the way to read from the file the first 10 information's through the array (not arraylist)ProdName and the quantity." plus that I stack in the in.readLine(); propably is not compatible with the StringTokenizer.
Now the other problem is that I need the quantity to be an integer instead of string.
The file includes something like that:
Ball 32
tennis 322
fireball 54
..
.
.
.
.
Any ideas?
I would place this in a helper function, maybe called parseString
class ProductNameQuan {
public static void main(String[] args)
{
...
try {
BufferedReader in = ...
line = in.readLine();
while (line != null) {
ProductNameQuan.parseString(line);
}
}
...
}
public static void parseString(String someString)
{
StringTokenizer st = new StringTokenizer(someString);
while (st.hasMoreTokens()) {
String token = line.nextToken();
try {
int quantity = Integer.parseInt(token)
// process number
} catch(NumberFormatException ex) {
// process string token
}
}
}
My file has:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
The code below does the following.
1. If line count equals num[index],it checks whether if that line contains the string from
VALUES1[index]. If true, it replace that string from the first index in VALUES[index] and writes to a new file.
2.If num index not equal num[index],it simply writes the line to new file as it is.
The problem am getting is that after writing to new file, original line 1 and 2 still appears in the new file. How to remove that.
Heres my code:
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {1,2,4}; //Line Numbers
String[] VALUES = new String[] {"AB","BC","CD"}; //Correct Solutions
String[] VALUES1 = new String[] {"class","void","System"}; //To Replace
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
String line1 = null;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Here is my result:
public AB MyC{
**public class MyC{ //This still appears.**
public BC MyMethod()
**public void MyMethod()//This still appears.**
{
CD.out.println("My method has been accessed");
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
you should add an indicator to show if this line is replaced
while(line!=null){
boolean exists = false;
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
exists = true;
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
if (!exists)
writer1.write(line+System.getProperty("line.separator"));
comment this line in code
writer1.write(line+System.getProperty("line.separator"));
then try