Read variable values from the file path - java

I would like get variable values from a file name.
For example, I have a folder of images with 2 sub folders called "photos_2011_mycamera" and "photos_2012_mycamera". I want to be able to read the year and then I will use it with the photos inside the folder. I was thinking in something like tokens where you can put
*$* and this would read the number in $ and take it as a variable (in this case the years 2011 and 2012).
I'm guessing that I will have problems with variables at the end of the path, not properly separated...
I use Java, but the problem would be the same in any other language, I guess.
I would appreciate any suggestion or tips of the best way to do this.
Thanks a lot!

Assuming you already have the file name in a variable called FileName you can use the split() method in Java to split up the string and add the different substrings to an array.
For example:
String FileName = "photos_2011_mycamera";
String type, year, name;
String[] dataArray = FileName.split("_") // Splits the string wherever a "_" occurs
type = dataArray[0];
year = dataArray[1];
name = dataArray[2];
System.out.println(type); //photos
System.out.println(year); //2011
System.out.println(name); //mycamera
Assuming your files will always be named in that format this method souhld work fine.

Related

Java set of path pretty output in console

Please advice good solution in Java how to pretty print in console Set of java.nio.file.Path.
For example:
Path:
/src/test/resources/TestFolder/Wave.java
/src/test/resources/TestFolder
/src/test/resources/TestFolder/Mello.java
/src/test/resources/TestFolder/TestFolder2/Dave2.java
/src/test/resources/TestFolder/TestFolder2/Hello2.java
/src/test/resources/TestFolder/TestFolder2
And expected result:
TestFolder
Wave.java
Mello.java
TestFolder2
Dave2.java
Hello2.java
There is no built in API call that would do this. Fortunately, Java is a programming language, and you're a programmer. Let's program it! :)
The tools you need:
relativize, or getFileName
You can use the relativize call to produce paths that are relative to a 'root point'. For example:
Paths.get("/src/test/resources").relativize(Paths.get("/src/test/resources/TestFolder/Mello.java"))
turns into a path representing: TestFolder/Mello.java.
However, perhaps you want each entry in your output to always only be just a single file name; in that case, the getFileName() call strips out all path elements except the lasts one: Paths.get("/src/test/resources/TestFolder/TestFolder2/Hello2.java").getFileName() produces a path with just Hello2.java (if you need it as string, just call toString() on the path object to get that).
StringBuilder
The StringBuilder class can be used to produce a longer string piece by piece.
repeat
If you have an int representing your 'nesting level', in your example you want a bunch of spaces in front of the filename equal to some multiple of that. You can use the repeat call to turn a number into a string containing that number of spaces: String prefix = " ".repeat(5); produces a string containing 10 spaces.
NB: This is somewhat newer API; if you're on an old version of java and this call does not work, you'd have to write it yourself. It's just a single for loop.
Files.isDirectory
To know if any given file is a directory, you can call that; it returns true if it is and false if it is not.
Files.newDirectoryStream
This is one way to 'walk' a file system: This lets you list each dir/file in a given directory:
Path somePathObject = Paths.get("/foo/bar");
try (var contents = Files.newDirectoryStream(somePathObject)) {
for (Path content : contents) {
.. this is called once for each file/dir in '/foo/bar'
}
}
recursion
Finally, to tie it all together: You'd want to walk through each child in a given starting point, if it is a file, print a number of spacers equal to our nesting level (which starts at 0), then the simple file name, and then move on to the next entry. For directory entries, you want to do that but then 'dive' into the directory, incrementing the nesting level. If you make the nesting level a parameter, you can call your own method, using the directory as new 'root point', and passing 'nestingLevel + 1' for the nesting level.
Good luck & Have fun!

Reading specific data from a line in a text file to respective arrays, in Java

This is in a text file
After each comma on the line, it’s a different piece of data, e.g.
the first data is first name, then surname, then contact number, then address, then college, then college id, then course, then specialization
I need to write a java program that will read the text file and for each line, and for each piece of data, will store the information into respective arrays in the program, for example, all the “first names” read will be stored in an array called “first name” and so on.
This was easy to for me to write in python using line.split(“,”) but java is totally different for me to understand
Yes you can also achieve this in java using split method by splitting the each line by separate in your case it is comma and you will get string array .Then iterate over the array and map your keys.
Consider below example
String line = "Amit, 29";
String []values = line.split(",");
String name = values[0];
String age = values[1];

How to get a value in a file with coordinates in Java

My programm needs to read a file that has different data structures with a variable separator.
In my properties-file you can set the separator and put coordinates for values of different variables:
separator = ;
variable1 = 1,7
variable2 = 2,42
I would like to have a way where I can access a column and a line with some kind of coordinates.
I'm thinking of a syntax like this:
file.get(1,7,";")
(Which would give you the value of the 1st line and 7th column with the specific separator)
Does someone know a library or a code snippet that does exactly this?
Using String.split() :
public String get(File file, int lineNumber, int column, String separator ) {
//getting to the lineNumber of the file ommitted
// suppose you got it in a String named "line"
return line.split(separator)[column - 1];
}
You can use OpenCSV or SuperCSV for example. I'm not aware of any library that does your 'coordinates' gettings, but it's as simple as reading the CSV with the given separator as List-of-Lists and then call
csv.get(1).get(7)
Seems to be a simple file processing, You should first process the file -
create ArrayList<ArrayList<String>> processedFile
Read every line, split using "line".split(separator)
Store the array above in the ArrayList processedFile at current index
increase the index with every line
Once processedFile is ready, you can simply use processedFile.get(row).get(column). Also once the file is processed, all the other queries will be O(1). Hints are enough, try writing the code yourself, you will learn more.
PS: Take care of NullPointerExceptions wherever required.

How do I insert String variable dynamically into a longer String variable?

I am trying to take a person's name from a text input field, send it to another Activity, and display that person's name in a sentence within a TextView.
My code is as follows:
This is in one of my Activities.
String meaningText = mCurrentColor.getMeaning();
meaningText = String.format(meaningText, mYourName);
mColorText.setText(meaningText);
I'm pulling the Meaning string from another class that would contain something along the lines of:
"Hey %1$s, you chose this which means blah blah....."
Then I want to insert that mYourName variable which is pulled from an EditText in a previous Activity and put that in the above string.
I found that formatting from a Team Treehouse tutorial and it worked in that project's code as I followed along.
I'm using the String.format which takes in a Locale.
I am not sure exactly what is wrong as I mirrored the code to a "T" and just changed some variable names.
Seeing as the String class' length() method returns an int value, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)
So you can have a String of 2,147,483,647 characters, theoretically. I don't think you should need much more than that.
However, Android system limits your heap space, going as low as 16 MB. Therefore, you'll never practically be able to reach the theoretical limit, and will max out with a String somewhere in the 4-64 million character range.
so, why are you thinking of a longer string variable, when you can directly use your name variable along with a string variable of long length.
for Ex:-
String meaning_text = "the very long message you wanted to show..."+ mYourName + "again a long message if you want to show";
so my suggestion is to use your name variable directly with message you wanted to show.
EditText edt=(EditText)findViewbyId(R.id.edt);
edt.setText("Dipali");
now,getting value from edittext and Replace in TextView String resource.
String strEdtTextValue=edt.getText().toString();
TextView tV=(TextView)findViewById(R.id.txtView)
Set text in textview as xml Resource like as
dummy="Hey %1$s, you chose this which means blah blah....."
add string in resource file
<string name="dummy">Hey %1$s, you chose this which means blah blah.....</string>
Resources res = getResources();
String dumyText= (res.getString(R.string.dummy),strEdtTextValue);
tv.setText(dumyText);
Its helpful to you.

Replace specific string in ArrayList with random string from another ArrayList

Im fairly new in programming java (just started a couple of months ago) and i am unfortunatly in a bit of confused state at the moment.
I am presently using BlueJ for my programming, and ive encountered a exercise in in my book which i do have some problems getting the grips of how to further add the wanted functionality.
The exercise has two previously made classes (ReaderInput & WriterOutput), and i am to create a new class which calls and makes use of the preceeding classes methods. The exercise includes two .txt files, one includes a story, and the second one includes differents kinds of adjectives(words). Then, i have to read the story.txt file, and replace Strings in that file with a specific value(a string with the value "ADJECTIVE"), with randomly chosen words from the adjectives.txt file, and finally, output them (write) to a completely new file.
A sample from the story.txt file:
'Once upon a time there was a ADJECTIVE girl who were in a ADJECTIVE birthday togheter with lots of ADJECTIVE friends etc....'
A sample from the adjectives.txt file:
whiny
old
little
stupid
etc...
So, i created a new class, added and initialized new field objects of the ReaderInput class, like so;
private ReaderInput reader;
private WriterOutput writer;
private Random random;
public StoryCreator()
{
reader = new ReaderInput();
writer = new WriterOutput();
random = new Random();
}
Then i created a new method called createAdjectiveStory with parameters to specify both the story filename and adjectives.
public void createAdjectiveStory(String storyFilename, String adjectivesFilename/*, String outputFilename*/)
Then, i declare two variables to hold the reader words from the ReaderInput class(specifying the file to read through parameters):
ArrayList<String> story = reader.getWordsInFile(storyFilename);
ArrayList<String> adjective = reader.getWordsInFile(adjectivesFilename);
Then here comes the big headache. While, i have been able to declare a String varible wordToChange = "ADJECTIVE"; , create a for-each loop to iterate over the story arraylist collection, with an if statement to check if string in element is equal to wordToChange. At last i made a random to go trough the adjective arryalist, and get a random word from the collection (This gets a random word from the file each time i call the method and print it individually)
for(String reader : story){
int index = random.nextInt(adjective.size());
String word = adjective.get(index);
if(reader.equals(wordToChange))
Collections.replaceAll(story,wordToChange,word);
}
}
In the if statement, i tried to use the replaceAll function, like so:
Collections.replaceAll(story,wordToChange,word);
The problem here is that if i try to print this out (just to verify that it works), i get this:
'Once upon a time there was a OLD girl who were in a OLD birthday togheter with lots of OLD friends etc....'
Now i rather want this.
'Once upon a time there was a OLD girl who were in a WHINY borthday togheter with lots of STUPID friends etc....'
Ive tried make use of the .replace function, like so:
Collections.replace(story,wordToChange,word);
But i get an error specifying: 'Cannot find symbol - method replace'.
I am quite stuck right about here, and i cannot seem to find the right solution for this. Ayone have any tips/tricks or solution for this?
New programmer needing a little "push" in the right direction. Any help will be appreciated highly:)
The problem is that it's choosing the word to change it to once and then the replaceAll is replacing every instance of REPLACE immediately.
What you should do instead is use an iterator in your for loop:
Iterator<String> i=story.iterator();
while (i.hasNext()) {
String check = i.next();
if (check.equals(stringToReplace)) {
i.set(getRandomAdjective());
}
}
You should create a method for your code to get a random adjective.

Categories