Java Scanner multiple delimiter - java

I know this is a very asked question but I can't find and apropiate answer for my problem. Thing is I have to program and aplication that reads from a .TXT file like this
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
My question is how what can I do to tell Java that I want String before : in one ArrayList and Strings after : in another ArrayList?? I guess It's using delimeter method but I don't know how use it in this case.
Sorry for my poor english, I've to improve It i guess. Thanks

use split function of java.
steps:
Declare two arrayList. l1 and l2;
read each line.
split each line by ":", this will return a array of length 2, array. (as per your input)
l1.add(array[0]) , l2.add(array1)
try yourself, post code if you need help :)
check here for use of split function, though through google you can find many different example

Split the string using ":" as delimiter. Add the odd entries from the result to one list and even to another list.

If your text is like this:
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
You can achieve what you want by using:
StringBuilder text = new StringBuilder();
Scanner scanner = new Scanner(new FileInputStream(fFileName), encoding); //try utf8 or utf-8 for 'encoding'
try {
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String before = line.split(":")[0];
String after = line.split(":")[1];
//dsw 'before' and 'after' - add them to lists.
}
}
finally{
scanner.close();
}

Scanner scanner = new Scanner(new FileInputStream("YOUR_FILE_PATH"));
List<String> firstList = new ArrayList<String>();
List<String> secondList = new ArrayList<String>();
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] tokenizedString = currentLine.split(":");
firstList.add(tokenizedString[0]);
secondList.add(tokenizedString[1]);
}
scanner.close();
Enumerating firstList and secondList will get you the desired result.

1. Use ":" as delimiter.
2. Then Store them in the String[] using split() function.
3. Try using BufferedReader instead of Scanner.
Eg:
File f = new File("d:\\Mytext.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
ArrayList<String> s1 = new ArrayList<String>();
ArrayList<String> s2 = new ArrayList<String>();
while ((br.readLine())!=null){
String line = br.readLine();
String bf = line.split(":")[0];
String af = line.split(":")[1];
s1.add(bf);
s2.add(af);
}

Related

Trying to get Scanner to scan entire file

String userInput = stdin.nextLine();
file = new File(userInput);
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNext()) {
fileContents = fileScanner.nextLine();
}
So I'm trying to figure out how I can get my variable fileContents to hold all of the file from the scanner. with the current way I have it setup the variable fileContents is left with only the last line of the .txt file. for what I'm doing I need it to hold the entire text from the file. spaces, chars and all.
I'm sure there is a simple fix to this I'm just very new to java/coding.
You need to change
fileContents += fileScanner.nextLine();
or
fileContents =fileContents + fileScanner.nextLine();
With your approach you are reassigning the fileContents value instead you need to concat the next line.
String userInput = stdin.nextLine();
file = new File(userInput);
StringBuilder sb = new StringBuilder();
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNext()) {
sb.append(fileScanner.nextLine()+"\n");
}
System.out.println(sb.toString());
Or follow the #singhakash's answer, because his one is faster performance wise I presume. But I used a StringBuilder to give you an idea that you're 'appending' or in other words, just adding to the data that you wish to use. Where as with your way, you're going to be getting the last line of the text because it keeps overriding the previous data.
You can use below as well:
Scanner sc = new Scanner(new File("C:/abc.txt"));
String fileContents = sc.useDelimiter("\\A").next();
You don't have to use while loop in this case.

How parse char character in java

My file
ABABCCC
My java code:
BufferedReader br = new BufferedReader(new FileReader("My file"));
StringTokenizer sr = new StringTokenizer(br.readLine());
char[] problem = null;
int i = 0;
while(sr.hasMoreTokens())
{
problem[i] = sr.nextToken();
i++;
}
desired output:
problem[0] = 'A'
problem[1] = 'B'
and so on
Please help me in this and provide me a good method for this.
You don't need a StringTokenizer for this data. Just read the data from the file into a String and convert it to a char array.
String line = br.readLine();
char[] problem = line.toCharArray();
You'd only need a loop to read this data if you had multiple lines in your file, or if you had multiple tokens to parse.
StingTokenizer doesn't split up a line by chars it will do it by tokens which is equivalent to words in a sentence. Here is an example usage of that class.
You can store the entire line into a string and then convert that into the char array you have setup.
String fileInput = br.readLine();
char[] problem = fileInput.toCharArray();
You shouldn't be using StringTokenizer, from the Javadoc -
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
If I understand what you're trying to do, here's one way to do it with a Scanner and String.toCharArray() -
Scanner sc;
char[] problem = null;
try {
sc = new Scanner(new File("My file"));
if (sc.hasNext()) {
problem = sc.next().toCharArray();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(problem));

Reading from a text file in Java

I have a text file like this:
Item 1
Item 2
Item 3
I need to be able to read each "Item X" into a string and ideally store all the strings as a vector / ArrayList.
I tried:
InputStream is = new FileInputStream("file.txt");
is.read(); //looped for every line of text
but that seems to only handle integers.
Thanks
You have several answers here, the easiest would be to us a Scanner (in java.util).
It has several convenience methods like nextLine() and next() and nextInt(), so you could simply do the following:
Scanner scanner = new Scanner(new File("file.txt"));
List<String> text = new ArrayList<String>();
while (scanner.hasNextLine()) {
text.add(scanner.nextLine());
}
Alternatively you could use a BufferedReader (in java.io):
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
List<String> text = new ArrayList<String>();
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
However Scanners are generally easier to work with.
You should use FileUtils to do this. It has a method named readLines
public static List<String> readLines(File file, Charset encoding) throws IOException
Reads the contents of a file line by line to a List of Strings. The file is always closed.
See #BackSlash's comment above to see how you're using InputStream.read() wrong.
#BackSlash also mentioned you can use java.nio.file.Files#readAllLines but only if you're using Java 1.7 or later.
You could use Java 7's Files#readAllLines. A short one-liner and no 3rd party library imports necessary :)
List<String> lines =
Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String [] tmp ;
while (line != null) {
sb.append(line);
tmp = line.Split(" ");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Scanner scan = new Scanner(new FileInputStream("file.txt"));
scan.nextLine();

Read in lines of text file to separate arrays using indexOf

I want to separate the elements of a text file into different arrays based of whether or not the line contains a question mark. Here is as far as I got.
Scanner inScan = new Scanner(System.in);
String file_name;
System.out.print("What is the full file path name?\n>>");
file_name = inScan.next();
Scanner fScan = new Scanner(new File(file_name));
ArrayList<String> Questions = new ArrayList();
ArrayList<String> Other = new ArrayList();
while (fScan.hasNextLine())
{
if(fScan.nextLine.indexOf("?"))
{
Questions.add(fScan.nextLine());
}
Other.add(fScan.nextLine());
}
Quite a few issues there
nextLine() actually returns the next line and moves on the scanner, so you'll need to read once instead
indexOf returns an int, not a boolean, I'm guessing you're more use to C++? You can use any of the following instead:
indexOf("?") >=0
contains("?")
matches("\?") etc.
please follow the java ways and use camelCase for vars...
Code
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("foo.txt"));
List<String> questions = new ArrayList<String>();
List<String> other = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("?")) {
questions.add(line);
} else {
other.add(line);
}
}
System.out.println(questions);
System.out.println(other);
}
foo.txt
line without question mark
line with question mark?
another line

how to print part of a string in Java

CODE:
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
ArrayList<String> massiiv = new ArrayList();
for (int i = 0; i < input.length(); i++)
massiiv.add(input[i]); // error here
HI!
How can I split the input and add the input to the data structure massiiv?
For instance, input is: "Where do you live?". Then the massiiv show be:
massiv[0] = where
massiv[1] = do
massiv[2] = you
THANKS!
The Java Documentation is your friend:
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
String[] myWords = input.split(" ");
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
String input = in.readLine();
String[] massiiv = input.split(" ");
Use a StringTokenizer, which allows an application to break a string into tokens.
Use space as delimiter, set the returnDelims flag to false such that space only serves to separate tokens. Then
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
prints the following output:
this
is
a
test
Try using split(String regex).
String[] inputs = in.readLine().split(" "); //split string into array
ArrayList<String> massiiv = new ArrayList();
for (String input : inputs) {
massiiv.add(inputs);
}
You would use the string.split() method in java. In your case, you want to split on spaces in the string, so your code would be:
massiiv = new ArrayList(input.split(" "));
If you don't want to have the word you in your output, you would have to do additional processing.
A one-line solution. Any amount of whitespace possible between the strings.
ArrayList<String> massiiv = new ArrayList(Arrays.asList(input.split("\\s+")));

Categories

Resources