Split text files - java

First of all I am new to Java.
I am trying to use the Split() function on a user specified txt file.
It should split the files using space to output a array of Strings.
I am using JFileChooser but I dont know how to perform Split on the selected txt file. I am using a Scanner to do this.
Please if someone can make the code finished, for some reason I cant get my head around it :-/
I have made it so far:
JFileChooser chooser = new JFileChooser("C:\\");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
".txt and .java files", "txt", "java");
chooser.setFileFilter(filter);
int code = chooser.showOpenDialog(null);
if (code == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
Scanner input;
try {
input = new Scanner(selectedFile);
while (input.hasNext()) {
String[] splits = input.next().split(" ");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

If you need to split the input by the space character, then include a string with a space instead of an empty string. Replace
String[] splits = f.split("");
with
String[] splits = f.split(" "); // One space
As others have pointed out, f isn't declared in your block. You'll have to declare it as a String and use your Scanner to read input into f, then use split.

f.split("");
or
f.split("[\\s]+");
to be safe with tabs and double spaces.

What is f? It's not declared anywhere, except as an Exception after having being used earlier, which makes no sense.
Your while loop should be written as this:
while (input.hasNextLine()) {
String line = input.nextLine();
String[] splits = line.split(" ");
// put the result of split somewhere
}

while (input.hasNext()) {
String[] splits = f.split("");
input.next();
}
System.out.println(f);
First of all, splits is never used. Second of all, input.next() is never stored in a variable. Also, I have no idea what f is. Try something like this:
while (input.hasNext()) {
String[] splits = input.next().split(" ");
someList.add(splits);
}
You could declare someList as something like new ArrayList<String[]>().

Related

Split comma separated values in java, int and String

I have the following in a text file to import into an ArrayList:
Australia,2
Ghana,4
China,3
Spain,1
My ArrayList is made up of objects from another class, Team which has the fields TeamName and ranking. I can get the following to import the String and int into the team name, but I can't separate the number which is supposed to be the teams ranking:
public void fileReader()
{
try
{
String filename = "teams.txt";
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
for (Team teams : teams)
{
teams.setTeamName(parser.next());
teams.setRanking(parser.next()); //this doesn't work
}
}
catch (IOException e)
{
System.out.println("Cannot find file");
}
}
I'm guessing I have to use a split somewhere along the line, or convert a String to an integer??
Check out opencsv. It's 2018 and you shouldn't have to parse a text file yourself :).
By default scanner will use white space as delimiter
Override this by calling useDelimiter method in your case parser.useDelimiter(',');
Then for converting ranking string to int you parser.nextInt()
You can code something like below to suite your purpose.
You have two tokens in your use case i.e. comma (,) and new line (\n). As a result, next() can't be used in a straight forward way.
I am going over each line, then tokenizing each line on comma and finally getting subsequent tokens.
try
{
String filename = "teams.txt";
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
for (Team teams : teams)
{
String[] splitLine = sc.nextLine().split(","); // comma delimited array
teams.setTeamName(splitLine[0]);
teams.setRanking(splitLine[1]);
}
}
Scanner.next() read the next token from input stream, and give String.
If you want to read the next integer, you should use nextInt() instead:
teams.setRanking(parser.nextInt());
Edit
You got InputMismatchException because by default, Scanner use java whitespace as delimeter.
WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+")
In your case, the delimeter are comma , and new line \n so you should config the delimeter for your scanner:
Scanner parser = new Scanner(inputFile);
s.useDelimiter(",|\\n")
Another work around is to read the whole line and parse your line:
String line = parse.nextLine();
String[] parts = line.split(",");
team.setTeamName(parts[0]);
team.setRanking(Integer.parse(parts[1]));
You can choose one of the two solutions above

change specific text in text file with scanner class (java)

I write this code that can search for the some specific text (such as word) in the text file with scanner class, but i want also to replace (old text to the new text) in the same old text locuation.
i find in the internet that i must used replaceAll method like ( replaceAll(old, new); )
but it does't work with the scanner class.
This is my code, it just search (if it existed ) write new text in new line without change the old one.
Do i need to change the method (to get the data) form scanner to FileReader ??
File file = new File("C:\\Users....file.txt");
Scanner input = new Scanner(System.in);
System.out.println("Enter the content you want to change:");
String Uinput = input.nextLine();
System.out.println("You want to change it to:");
String Uinput2 = input.nextLine();
Scanner scanner = new Scanner(file).useDelimiter(",");
BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));
while (scanner.hasNextLine()) {
String lineFromFile = scanner.next();
if (lineFromFile.contains(Uinput)) {
lineFromFile = Uinput2;
writer.write(lineFromFile);
writer.close();
System.out.println("changed " + Uinput + " tO " + Uinput2);
break;
}
else if (!lineFromFile.contains(Uinput)){
System.out.println("Don't found " + Uinput);
break;
}
}
You cannot read from a file, then write to that same file. You need 2 different files.
while (read line from input file) {
if (NOT matches your search pattern)
write line to output file.
else { // matches
write start of line to your search pattern.
write your replace string
write from end of search pattern to end of line.
}
}
Unless your replace string is the same size as your search string, yes, you'll have to use 2 files. Consider the file:
Blah
Blah
Blah
Now replace the letter 'a' with "The quick Brown Fox". If you replace the first line, you've overwritten the rest of the file. Now you can't read the 2nd line, so YES, you'll have to use 2 files.
Here's another answer based on #Sedrick comment and your code.
I'm adding it to your pseudo code.
File file = new File("C:\\Users....file.txt");
Scanner input = new Scanner(System.in);
System.out.println("Enter the content you want to change:");
String Uinput = input.nextLine();
System.out.println("You want to change it to:");
String Uinput2 = input.nextLine();
Scanner scanner = new Scanner(file).useDelimiter(",");
java.util.List<String> tempStorage = new ArrayList<>();
while (scanner.hasNextLine()) {
String lineFromFile = scanner.next();
tempStorage.add(lineFromFile);
}
// close input file here
// Open your write file here (same file = overwrite).
// now loop through temp storage searching for input string.
for (String currentLine : tempStorage ) {
if (!lcurrentLine.contains(Uinput)){
String temp = currentLine.replace(Uinput, Uinput2);
write a line using temp variable
} else { // not replaced
write a line using currentLine;
}
// close write file here
By the way, you'll have to encase the reads writes with try catch to trap for IOExceptions. That's how I knew it was pseudo code. There are plenty of examples for reading/writing a file on this web site. It's easy to search for.

Read text from file line by line to 2 strings variables

I have a file with some words saved in a text file like that:
Koraa
Orakaa
Balaes
Ealaaab
Araqko
I need to know how to read it using Java like below:
string firstWord = "Koraa";
and the 2nd line in another string
string secondWord = "Orakaa";
then I will do some stuff on those 2 strings then secondWord & firstWord contents' will be replaced with next 2 lines in the same file !
for example:
firstWord = "Balaes";
secondWord = "Ealaaab";
... etc the operation will be looping on all these words.
You can have an ArrayList of String and read separate lines from a file using Scanner.
List<String> al = new ArrayList<String>();
File file = new File("example.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
al.add(scanner.nextLine())
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
}
You can refer to the individual words, in order, with al.get(int index).

Read file from txt and split string using comma

Why is it it says that there is no split method found ? I want to split one lines to several parts. But there is error. Why is that so ?
try {
Scanner a = new Scanner (new FileInputStream ("product.txt"));
while (a.hasNext()){
System.out.println(a.nextLine()); //this works correctly, all the lines are displayed
String[] temp = a.split(",");
}
a.close();
}catch (FileNotFoundException e){
System.out.println("File not found");
}
split() is not defined for Scanner but for String.
Here's a quick fix:
String line = a.nextLine();
System.out.println(line); //this works correctly, all the lines are displayed
String[] temp = line.split(",");
split method works on the String and not on the Scanner. So store the contents of
a.nextLine()
in a string like this
String line = a.nextLine();
and then use split method on this stirng
String[] temp = line.split(",");

how to read the \n in a txt file for using in split

I have this code here
java.io.File file=new java.io.File("deneme2.txt");
try{
Scanner input=new Scanner(file);
while(input.hasNext()){
String inputFile= input.nextLine();
String[] sequences =inputFile.split(" ");
It reads the file but I have to edit each file since I can not read .txt when the input is like this
ATGAGATACG
AGTCTCTAG
but I can read when I make
ATGAGATACG AGTCTCTAG
I tried to make \n and something like that but I couldn't.
So can you guys help me.
AND I know for sure that it has a very simple solution :) a solution that I'm not aware of tho
edit:in first example the 2 sequences are divided with a shift enter but the second one is divided with a single space
It sounds like you want to make the code that reads the file independent of the file format. To some extent, that's not possible. Any program has to assume some kind of pattern to the input -- be it XML, delimited text etc. So that breaks it up into two approaches: Either make the file fit the code or make the code fit the file.
From your description, I'm guessing you want to be able to read a sequence of characters that is delimited by whitespace -- any whitespace (' ', '\n', '\t'), yes? If that's true, don't limit yourself to reading by line. Just read each token. This, of course, assumes each token is what you want.
I created a test file with the content
abcd efg h
ijklm op
qrs
That has newlines, spaces and tabs. Then I fed it to the following code:
public static void main(String[] args){
try{
Scanner scanner = new Scanner(new File("testFile.txt"));
List<String> list = new ArrayList<String>();
while(scanner.hasNext()){
String s = scanner.next();
list.add(s);
}
scanner.close();
System.out.println(list);
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
Which gives the output
[abcd, efg, h, ijklm, op, qrs]
Is it possible you want to create an array of sequences? Like you want this file
ATGAGATACG <-- each of these being a sequence
AGTCTCTAG
to become an array like this
String[] sequences = {"ATGAGATACG", "AGTCTCTAG"};
If that's the case, you can just do something like this
List<String> sequences = new ArrayList<String>(); <-- create a list
java.io.File file=new java.io.File("deneme2.txt");
try{
Scanner input = new Scanner(file);
while(input.hasNextLine()){
sequences.add(input.nextLine().trim()); <-- add to the list each line
}
Edit
If its only two lines why not just do this, and forget the loop
String s1;
String s2;
try {
Scanner input = new Scanner(file);
s1 = input.nextLine().trim();
s2 = input.nextLine().trim();
} catch(.. ){
}
// do something with s1
// do something with s2

Categories

Resources