I am working on project where I need to copy some part of each line from 1st text file to other. In the first text each data is separated by splitter --# (which i have used).
I want to get the 1st two parts of actual 4 parts total of 3 splitters Ex:
Hello--#StackOverflow--#BMWCar--#Bye.
I just want to fetch 1st 2 parts .ie.
Hello--#StackOverflow
from all the lines of first text file to second text file. I have tried everything and could not get it to work. Please help me out of this. :)
I am little late, but below code will work as well :
String str = "Hello--#StackOverflow--#BMWCar--#Bye.";
String strResult = str.split("(?<!\\G\\w+)(?:--#)")[0];
System.out.println(strResult);
\G is previous match, (?<!regex) is negative lookbehind.
[Update]
In your case, can we use below code? The solution is based on the file you provided
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test{
public static void main (String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("abc.txt"));
String line;
while((line = in.readLine()) != null)
{
System.out.println(line.substring(0,line.lastIndexOf("--#")));
}
in.close();
}
}
For each line you read do the following:
String[] sp = line.split("--#",2);
String result = sp[0]+"--#"+sp[1];
If you're expecting names with dashes, it seems to me the best thing to use is String.split:
String test = "Hel-lo--#StackOverflow--#BMWCar--#Bye";
String[] sp = test.split("--#");
for(String name : Arrays.copyOfRange(sp, 0, 2))
{
System.out.println(name);
}
First, to get all the lines in the text file, try using a while loop. As you are reading in from one file, output to the second file. Split each line based on the conditional.
String inLine = in.nextLine();
String[] parts = inLine.split("--#");
String toWrite = parts[0] + " " + parts[1];
outLine.write(toWrite);
Should be easy enough to figure out.
Related
I'm working with a large text file that has thousands of lines of text that contain some information. Sometimes the software will randomly add a character in place which will fail our upload. I'm trying to create a program that finds a string that is hard coded and then searches within the line and replaces or removes the invalided character. Here is some of the contents of the text file.
MTR17000386001000000000000000RA 124359
00010000004000000040000000 000NN NNE 000 N
RDG17000386
KWHL000000000R00000100000059534000405162019075929N000400000010N8486
000010500R 00000010010000059226
RFF1700038652126007 ERT
0000000952.0062500070014051620190759290005953476Type 7 0000N 6
MTR17000386001000000000000000RA 114818
00010000005000000050000000 000NN NNE 000 N
RDG17000386
DMDL000000000R000001000.0072666035305162019112344N000100000010N8486
005180500R 00000010010000072666
RFF1700038611861733 ERT
0000000952.0062500070000051620191123440007266680Type 7 0000N 6
On the line of RDG17000386 DMD you can see that there is a period. The period is not supposed to be there and needs to be replaced or removed from the file.
In my current code I"m searching each line that start with "RDG" and it works find, but I want to limit the search with only the lines that include "DMD" within the line and I've tried changing the RDG to DMD, which didn't work because the line doesn't start with DMD. I'm not entirely sure how to remove or replace the period from the file. Here is what my code looks like so far.
import java.io.*;
public class ReadLineAndReplace {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("RDG")) {
//assuming the replace would be inserted here
System.out.println(line);
}
}
}
}
Use. matches() with a regular expression
line.matches("^RDG.*DMD.*")
to replace the dot with a zero
if (line.matches("^RDG.*DMD.*")) {
line = line.replace('.', '0')
}
I am currently testing out a program who's purpose is to import a file and find the number of characters in that file using string manipulation.
I am currently using System.out.println(fileone.length()); to do so. However each time I try and run the program it reads the number of characters wrong, in fact it gives the same wrong number every time. Down below is the output of the program.
My name is Sam Tyler 54
As you can see the words in the file are displayed and next to that is the character number which is obviously wrong, as I counted myself, it should be 19, including spaces.
Here is the code that is reading the file and giving the character number.
Can you see any problems?
Any help is much appreciated.
Scanner ourScanner = new Scanner(new File(fileone));
System.out.println();
while(ourScanner.hasNextLine())
{
System.out.print (ourScanner.nextLine() + "\t");
count++;
if (count%4 == 0)
System.out.println();
}
}
//System.out.println ("\n\n" + count + " \ntotal strings found.");
System.out.println(fileone.length());
You are checking the length of the String representing the file path (fileone), not the actual file scanned, so it will be invariant given the context.
If you're counting the number of lines, just print your count variable.
You also have a number of ways to check for file length from a File object , or for specific character length (since the file system may allocate more space than actually used for the file), you can count them through iteration with a FileReader, etc.
fileone.length() gives you the length of the path of file.
But new File(fileone).length() will give you the file size in number of bytes (assuming one character is one byte)
Try this example:
1: read all the lines of the file
2: convert to a string
3: remove the white spaces
4: display the length in byte for the resulting string
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("C:\\Users\\xxx\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuffer fileContents = new StringBuffer();
String line = br.readLine();
while (line != null) {
fileContents.append(line);
line = br.readLine();
}
String sValue = fileContents.toString();
//remove all whitespace
sValue = sValue.replaceAll("\\s+","");
System.out.println(sValue.length());
}
}
Test:
test.txt content: My name is Sam Tyler 54 --> 18 characters
result:
18
Why does Java String.split() generate different results when working with string defined in code versus string read from a file when numbers are involved? Specifically I have a file called "test.txt" that contains chars and numbers separated by spaces:
G H 5 4
The split method does not split on spaces as expected. But if a string variable is created within code with same chars and numbers separated by spaces then the result of split() is four individual strings, one for char and number. The code below demonstrates this difference:
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class SplitNumber {
//Read first line of text file
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fr);
String firstLine;
if ((firstLine = bufferedReader.readLine()) != null) {
String[] firstLineNumbers = firstLine.split("\\s+");
System.out.println("First line array length: " + firstLineNumbers.length);
for (int i=0; i<firstLineNumbers.length; i++) {
System.out.println(firstLineNumbers[i]);
}
}
bufferedReader.close();
String numberString = "G H 5 4";
String[] numbers = numberString.split("\\s+");
System.out.println("Numbers array length: " + numbers.length);
for (int i=0; i<numbers.length; i++) {
System.out.println(numbers[i]);
}
} catch(Exception exception) {
System.out.println("IOException occured");
exception.printStackTrace();
}
}
}
The result is:
First line array length: 3
G
H
5 4
Numbers array length: 4
G
H
5
4
Why do the numbers from the file not get parsed the same as the same string defined within code?
Based on feedback I changed the regex to split("[\\s\\h]+") which resolved the issue; the numbers for the file were properly split which clearly indicated that I had a different whitespace-like character in the text file that I was using. I then replaced the contents of the file (using notepad) and reverted back to split("\\s+") and found that it worked correctly this time. So at some point I must have introduced different white-space like characters in the file (maybe a copy/paste issue). In the end the take away is I should use split("[\\s\\h]+") when reading from a file where I want to split on spaces as it will cover more scenarios that may not be immediately obvious.
Thanks to all for helping me find the root cause of my issue.
I´m in a bit of a struggle here, I´m trying to add each word from a textfile to an ArrayList and every time the reader comes across the same word again it will skip it. (Makes sense?)
I don't even know where to start. I kind of know that I need one loop that adds the textfile to the ArrayList and one the checks if the word is not in the list. Any ideas?
PS: Just started with Java
This is what I've done so far, don't even know if I'm on the right path..
public String findWord(){
int text = 0;
int i = 0;
while sc.hasNextLine()){
wordArray[i] = sc.nextLine();
}
if wordArray[i].contains() {
}
i++;
}
A List (an ArrayList or otherwise) is not the best data structure to use; a Set is better. In pseudo code:
define a Set
for each word
if adding to the set returns false, skip it
else do whatever do want to do with the (first time encountered) word
The add() method of Set returns true if the set changed as a result of the call, which only happens if the word isn't already in the set, because sets disallow duplicates.
I once made a similar program, it read through a textfile and counted how many times a word came up.
Id start with importing a scanner, as well as a file system(this needs to be at the top of the java class)
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;
then you can make file, as well as a scanner reading from this file, make sure to adjsut the path to the file accordingly. The new Printstream is not necessary but when dealing with a big amount of data i dont like to overflow the console.
public static void main(String[] args) throws FileNotFoundException {
File file=new File("E:/Youtube analytics/input/input.txt");
Scanner scanner = new Scanner(file); //will read from the file above
PrintStream out = new PrintStream(new FileOutputStream("E:/Youtube analytics/output/output.txt"));
System.setOut(out);
}
after this you can use scanner.next() to get the next word so you would write something like this:
String[] array=new String[MaxAmountOfWords];//this will make an array
int numberOfWords=0;
String currentWord="";
while(scanner.hasNext()){
currentWord=scanner.next();
if(isNotInArray(currentWord))
{
array[numberOfWords]=currentWord
}
numberOfWords++;
}
If you dont understand any of this or need further guidence to progress, let me know. It is hard to help you if we dont exactly know where you are at...
You can try this:
public List<String> getAllWords(String filePath){
String line;
List<String> allWords = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));
//read each line of the file
while((line = reader.readLine()) != null) {
//get each word in the line
for(String word: line.split("(\\w)+"))
//validate if the current word is not empty
if(!word.isEmpty())
if(!allWords.contains(word))
allWords.add(word);
}
}
return allWords;
}
Best solution is to use a Set. But if you still want to use a List, here goes:
Suppose the file has the following data:
Hi how are you
I am Hardi
Who are you
Code will be:
List<String> list = new ArrayList<>();
// Get the file.
FileInputStream fis = new FileInputStream("C:/Users/hdinesh/Desktop/samples.txt");
//Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
// Loop through each line in the file
while ((line = br.readLine()) != null) {
// Regex for finding just the words
String[] strArray = line.split("[ ]");
for (int i = 0; i< strArray.length; i++) {
if (!list.contains(strArray[i])) {
list.add(strArray[i]);
}
}
}
br.close();
System.out.println(list.toString());
If your text file has sentences with special characters, you will have to write a regex for that.
Im trying to search a csv file for a specific string. I want to print out all entries in the csv that have a specific module in the line in the csv but I cant seem to get it working. Also is it possible to print out the out in one JOptionPane window instead of a different window for every result.
Csv format
12175466, C98754, B
12141895, CS4054, B
12484665, CS3054, B
18446876, CS1044, B
User Input: CS4054
Desired Results: 12141895, CS4054, B
public static void DisplayResults() throws IOException
{
String line;
String stringToSearch = JOptionPane.showInputDialog(null, "Enter the module code ");
BufferedReader in = new BufferedReader( new FileReader("StudentResults.csv" ) );
line = in.readLine();
while (line != null)
{
if (line.startsWith(stringToSearch))
{
JOptionPane.showMessageDialog(null, line );
}
line = in.readLine();
}
in.close();
Do you mean to use startswith? Maybe try contains.
How about this?
String theAnswer="";
if (line.contains(stringToSearch)) {
theAnswer += line +"\n";
}
JOptionPane.showMessageDialog(null, theAnswer);
Your CSV file has a specific format: Values separated by a comma. So you can split each line into an array and check the second value.
String[] values = line.split(",");
if(values[1].trim().equals(stringToSearch))
JOptionPane.showMessageDialog(null, line );
EDIT:
Use the above code, when you're sure, the user always types in the second value. If you want to search over all entries use this:
for (String val : values)
if(val.trim().equals(userInput))
JOptionPane.showMessageDialog(null, line );