Reading an array from file. (java) - java

Hello it is my code to read from file
case 11: {
String line;
String temp[];
System.out.println("Podaj nazwę pliku z jakiego odczytać playlistę.");
nazwa11 = odczyt.next();
try {
FileReader fileReader = new FileReader(nazwa11);
BufferedReader bufferedReader = new BufferedReader(fileReader);
playlists.add(new Playlist(bufferedReader.readLine()));
x++;
while((line = bufferedReader.readLine())!=null){
String delimiter = "|";
temp = line.split(delimiter);
int rok;
rok = Integer.parseInt(temp[2]);
playlists.get(x).dodajUtwor(temp[0], temp[1], rok);
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Nie znaleziono pliku: '" + nazwa11 + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + nazwa11 + "'");
}
break;
}
Example file looks like this:
Pop
Test|Test|2010
Test1|Test1|2001
Gives me error
Exception in thread "main" java.lang.NumberFormatException: For input string: "s"
Why my line.split doesn't split when it finds "|"? I guess it splits t-e-s, any tips?

The pipe character "|" is one of the meta characters that carries a special meaning while performing the match.
This page gives you the complete lists of these special characters and their meanings.
So, in your program, modify the following line,
String delimiter = "|";
to
String delimiter = "\\|";
This will give you the result that you want.

Related

Java - write string to file line by line vs one-liner / cannot convert String to String[]

Relatively new to programming. I want to read a URL, modify the text string, then write it to a line-separated csv textfile.
The read & modify parts run. Also, outputting the string to terminal (using Eclipse) looks fine (csv, line by line), like this;
data_a,data_b,data_c,...
data_a1,data_b1,datac1...
data_a2,data_b2,datac2...
.
.
.
But I'm unable to write the same string to file - it just becomes a one-liner (see my below for-loops, attempts no. 1 & 2);
data_a,data_b,data_c,data_a1,data_b1,datac1,data_a2,data_b2,datac2...
I guess I'm looking for a way to, in the FileWriter or BufferedWriter loops, convert the string finalDataA to array string (i.e. include the string suffix "[0]") but I have not yet found such an approach that would not give errors of the type "Cannot convert String to String[]". Any suggestions?
String data = "";
String dataHelper = "";
try {
URL myURL = new URL(url);
HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();
if (myConnection.getResponseCode() == URLStatus.HTTP_OK.getStatusCode()) {
BufferedReader in = new BufferedReader(new InputStreamReader(myConnection.getInputStream()));
while ((data = in.readLine()) != null) {
dataHelper = dataHelper + "\n" + data;
}
in.close();
String trimmedData = dataHelper.trim().replaceAll(" +", ",");
String parts[] = trimmedData.split(Pattern.quote(")"));// ,1.,");
String dataA = parts[1];
String finalDataA[] = dataA.split("</PRE>");
// parts 2&3 removed in this example
// Console output for testing purpose - This prints out many many lines of csv-data
System.out.println(finalDataA[0]);
//This returns the value 1
System.out.println(finalDataA.length);
// Attempt no. 1 to write to file - writes a oneliner
for(int i = 0; i < finalDataA.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(pathA, true))) {
String s;
s = finalDataA[i];
bw.write(s);
bw.newLine();
bw.flush();
}
}
// Attempt no. 2 to write to file - writes a oneliner
FileWriter fw = new FileWriter(pathA);
for (int i = 0; i < finalDataA.length; i++) {
fw.write(finalDataA[i] + "\n");
}
fw.close();
}
} catch (Exception e) {
System.out.println("Exception" +e);
}
Create the BufferedWriter and the FileWriter ahead of the for loop, not every time around it.
From your code comments, finalDataA has one element, so the for-loop will be executed only once. Try splitting finalDataA[0] into rows.
Something like this:
String endOfLineToken = "..."; //your variant
String[] lines = finalDataA[0].split(endOfLineToken)
BufferdWriter bw = new BufferedWriter(new FileWriter(pathA, true));
try
{
for (String line: lines)
{
bw.write(line);
bw.write(endOfLineToken);//to put back line endings
bw.newLine();
bw.flush();
}
}
catch (Exception e) {}

searching in text file specific words using java

I've a huge text file, I'd like to search for specific words and print three or more then this number OF THE WORDS AFTER IT so far I have done this
public static void main(String[] args) {
String fileName = "C:\\Users\\Mishari\\Desktop\\Mesh.txt";
String line = null;
try {
FileReader fileReader =
new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
} catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}
It's only for printing the file can you advise me what's the best way of doing it.
You can look for the index of word in line using this method.
int index = line.indexOf(word);
If the index is -1 then that word does not exist.
If it exist than takes the substring of line starting from that index till the end of line.
String nextWords = line.substring(index);
Now use String[] temp = nextWords.split(" ") to get all the words in that substring.
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if (line.contains("YOUR_SPECIFIC_WORDS")) { //do what you need here }
}
By the sounds of it what you appear to be looking for is a basic Find & Replace All mechanism for each file line that is read in from file. In other words, if the current file line that is read happens to contain the Word or phrase you would like to add words after then replace that found word with the very same word plus the other words you want to add. In a sense it would be something like this:
String line = "This is a file line.";
String find = "file"; // word to find in line
String replaceWith = "file (plus this stuff)"; // the phrase to change the found word to.
line = line.replace(find, replaceWith); // Replace any found words
System.out.println(line);
The console output would be:
This is a file (plus this stuff) line.
The main thing here though is that you only want to deal with actual words and not the same phrase within another word, for example the word "and" and the word "sand". You can clearly see that the characters that make up the word 'and' is also located in the word 'sand' and therefore it too would be changed with the above example code. The String.contains() method also locates strings this way. In most cases this is undesirable if you want to specifically deal with whole words only so a simple solution would be to use a Regular Expression (RegEx) with the String.replaceAll() method. Using your own code it would look something like this:
String fileName = "C:\\Users\\Mishari\\Desktop\\Mesh.txt";
String findPhrase = "and"; //Word or phrase to find and replace
String replaceWith = findPhrase + " (adding this)"; // The text used for the replacement.
boolean ignoreLetterCase = false; // Change to true to ignore letter case
String line = "";
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
if (ignoreLetterCase) {
line = line.toLowerCase();
findPhrase = findPhrase.toLowerCase();
}
if (line.contains(findPhrase)) {
line = line.replaceAll("\\b(" + findPhrase + ")\\b", replaceWith);
}
System.out.println(line);
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file: '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file: '" + fileName + "'");
}
You will of course notice the escaped \b word boundary Meta Characters within the regular expression used in the String.replaceAll() method specifically in the line:
line = line.replaceAll("\\b(" + findPhrase + ")\\b", replaceWith);
This allows us to deal with whole words only.

Replace specific string by another - String#replaceAll()

I'm actually developping a parser and I'm stuck on a method.
I need to clean specifics words in some sentences, meaning replacing those by a whitespace or a nullcharacter.
For now, I came up with this code:
private void clean(String sentence)
{
try {
FileInputStream fis = new FileInputStream(
ConfigHandler.getDefault(DictionaryType.CLEANING).getDictionaryFile());
BufferedReader bis = new BufferedReader(new InputStreamReader(fis));
String read;
List<String> wordList = new ArrayList<String>();
while ((read = bis.readLine()) != null) {
wordList.add(read);
}
}
catch (IOException e) {
e.printStackTrace();
}
for (String s : wordList) {
if (StringUtils.containsIgnoreCase(sentence, s)) { // this comes from Apache Lang
sentence = sentence.replaceAll("(?i)" + s + "\\b", " ");
}
}
cleanedList.add(sentence);
}
But when I look at the output, I got all of the occurences of the word to be replaced in my sentence replaced by a whitespace.
Does anybody can help me out on replacing only the exact words to be replaced on my sentence?
Thanks in advance !
There are two problems in your code:
You are missing the \b before the string
You will run into issues if any of the words from the file has special characters
To fix this problem construct your regex as follows:
sentence = sentence.replaceAll("(?i)\\b\\Q" + s + "\\E\\b", " ");
or
sentence = sentence.replaceAll("(?i)\\b" + Pattern.quote(s) + "\\b", " ");

Why does a blank line in a text file cause java.util.NoSuchElementException?

If you have a text file:
AAA:123:123:AAAA
BBB:456:456:BBBB
At first when there is no blank line in the text file and you read and retrieve data. Everything is fine.
When you write the file into a new file and replaces the data or update
AAA:9993:9993:AAAA
BBB:456:456:BBBB
-------- This is a blank line-----------
After this happens, NoSuchElementException will pop out. If the blank line is not removed, the error will always pop out.
try {
File fileCI = new File("CI.txt");
FileWriter fileWriter = new FileWriter(fileCI);
BufferedWriter bw = new BufferedWriter(fileWriter);
for (Customer ci : custList){
if (inputUser.equals(ci.getUserName()) && inputPass.equals(ci.getPassword())) {
ci.setCardNo(newCardNo);
ci.setCardType(newCardType);
}
String text = ci.getRealName() + ";" + ci.getUserName() + ";" + ci.getPassword() + ";" + ci.getAddress() + ";" + ci.getContact() + ";" + ci.getcardType() + ";" + ci.getcardNo() + System.getProperty("line.separator");
bw.write(text);
}
bw.close();
fileWriter.close();
}
catch (IOException e) {
e.printStackTrace();
}
if I dont add the System.getProperty("line.separator"); The String will be added and everything will be combined together into a line without a new separator. But this separator adds a blank line at the end of the text file. Is there anything I can do to avoid this problem?
Should I solve at the place where I read the file? Or solve it at the place where I write the file into a new file.
try {
Scanner read = new Scanner(file);
read.useDelimiter(";|\n");
String tmp = "";
while (read.hasNextLine()){
if (read.hasNext()){
custList.add(new Customer(read.next(), read.next(), read.next(), read.next(), read.next(), read.next(), read.next()));
} else {
break;
}
}
read.close();
}
catch (IOException e) {
e.printStackTrace();
}
Edit: This above read works perfectly now!
I think you reach at the end of file(EOF) where there is no remaining line and you still trying to read line . So you getting NoSuchElementException(if no line was found ).
Try this:
String tmp="";
while (reader.hasNextLine()){
tmp = s.nextLine();
// then do something
}
I think you dont have to use \n in delimiter. Since we are using scanner.hasNextLine(). If you want to use scanner.next(). Then
read.useDelimiter(";|\n");
Above line should be:
read.useDelimiter(";|\\n");// use escape character.
And loop this way.
while(s.hasNext()){
//do something.
}

I need to parse through a string and pull out information to input into a database

here is the edifile:
ISA*00* 00 *02*HMES *ZZ*MGLYNNCO *120321*1220*U*00401*000015676*0*P*:~GS*FA*HMES*MGLYNNCO*20120321*1220*15691*X*004010~ST*997*000015730~AK1*SM*18292~AK2*204*182920001~AK5*A~AK9*A*1*1*1~SE*6*000015730~GE*1*15691~IEA*1*000015676~
IN JAVA
I have an EDI file that I need to parse through. I can get the file and I have converted it to a string and used tokenizer to break it apart, the issue I am unsure of is that there is another delimiter for each segment how can I break it apart at the segment delimiter?
public class EdiParserP {
public static void main(String[] args) {
//retrieves the file to be read
File file = new File(args[0]);
int ch;
StringBuffer strContent = new StringBuffer("");
FileReader fileInSt = null;
try{
fileInSt = new FileReader(file);
while ((ch = fileInSt.read()) != -1)strContent.append((char)ch);
fileInSt.close();
}
catch (FileNotFoundException e)
{
System.out.println("file" + file.getAbsolutePath()+ "could not be found");
}
catch (IOException ioe) {
System.out.println("problem reading the file" + ioe);
}
System.out.println("File contents:" + "\n" + strContent + "\n");//used to check to see if file is there
System.out.print("Length of file" +" " + strContent.length()+ "\n"+ "\n");//used to count the length of the file
String buffFile = strContent.toString();//used to convert bufferstring to string
//breaks apart the file with the given delimiter
StringTokenizer st = new StringTokenizer(buffFile , "*");
while(st.hasMoreTokens())
{
String s =st.nextToken();
System.out.println(s);
}
}
}
I guess then my second question is how to retrieve the information to put into a database, I do know how to connect to the database, and how to insert, i think, i just am unsure how to pull the data out of this string? thanks for the help
Maybe it won't help you to the end, but using a StringTokenizer class is rather deprecated, you should use simple split() method of String class.
To be honest, I don't know what you really want to do with that file. Do you want to split each string received from StringTokenizer class once again?

Categories

Resources