OK, two good questions.
Most songs (but not all) begin and end on the same chord, which is the key of the song. So, if the song begins and ends on a D chord, the key is likely D. Also, melodies usually begin and end on notes that are in the I chord of the key. So if the song begins and ends on a D F# or A, it is likely in the key of D.
Or, if the chords seem to be different, but all the melody notes are in a certain key, it is likely in the key that all those melody notes belong to.
It is more common for a song to begin on another chord but end on a I chord. Such as midnight special, which is IV I V I or rag mama rag, which is VI II V I.
BUT!!!!
There are many exceptions!
The only good answer is, the more "puzzles" of this sort you solve, the more likely you can solve more. Is there a specific song/piece/tune/etude that you are trying to figure out?
Also, if it is written music, don't forget that the key signature is usually a dead giveaway.
Now, for your question of flats vs sharps.
Many pitches can be represented by either flats or sharps. For instance F# is also Gb. D# is also Eb. In a way, these issues are arbitrary. The note sounds the same, but we put a different label on it according to the context in which it is presented.
Because the classical guitar (which I notice you are studying) has open E A D G B E strings. (all of those keys have sharps in it) Guitarists are likely to play in keys that have sharps in it. Like G, D, E, A. That way, we get to use our open strings and play idiomatic things that fit well on our instruments.
Horn players like clarinet, trumpet, sax, french horn, trombone, etc...more naturally blow in flat keys like F, Bb, Eb, Ab or C (which has no sharps or flats)
That means, when people in each of these cultures extend themselves into foreign keys (like B, F#/Gb, C#/Db, G#/Ab, they are likely to use either sharps or flats to label it according to what is comfortable to them.