I'm trying to find an object in a list from a text file
Example:
L;10;€10,50;83259875;YellowPaint
-H;U;30;€12,00;98123742;Hammer
G;U;80;€15,00;87589302;Seeds
By inserting 98123742 by input with scanner, i want to find that string.
I tried to do this:
private static void inputCode() throws IOException {
String code;
String line = null;
boolean retVal = false;
System.out.println("\ninsert code: ");
code = in.next();
try {
FileReader fileReader = new FileReader("SHOP.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
String[] token = line.split(";");
if (token[0].equals(code) && token[1].equals(code)) {
retVal = true;
System.out.println(line);
}
}
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("impossible open the file " + fileName);
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
System.out.println(retVal);
}
How can i print "-H;U;30;€12,00;98123742;Hammer" inserting "98123742" (that is the code of the product) ?
Why are you splitting in the first place? For such a simple usecase, and with that line format, I'd go with
line.contains(";" + code);
Not much else to do.
Related
This program is meant to see two files located in a particular folder and then merge those two files and create a third file which is does. From the third merged file it is then searching for a keyword such as "test", once it finds that key word it prints out the location and the line of the keyword which is what is somewhat doing. What is happening is when I run the program it stops after the finds the keyword the first time in a line but it will not continue to search that line. So if there is multiple keyword 'test' in the line it will only find the first one and spit back the position and line. I want it to print both or multiple keywords. I think it is because of the IndexOf logic which is causing the issue.
import com.sun.deploy.util.StringUtils;
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Concatenate {
public static void main(String[] args) {
String sourceFile1Path = "C:/Users/me/Desktop/test1.txt";
String sourceFile2Path = "C:/Users/me/Desktop/test2.txt";
String mergedFilePath = "C:/Users/me/Desktop/merged.txt";
File[] files = new File[2];
files[0] = new File(sourceFile1Path);
files[1] = new File(sourceFile2Path);
File mergedFile = new File(mergedFilePath);
mergeFiles(files, mergedFile);
stringSearch(args);
}
private static void mergeFiles(File[] files, File mergedFile) {
FileWriter fstream = null;
BufferedWriter out = null;
try {
fstream = new FileWriter(mergedFile, true);
out = new BufferedWriter(fstream);
} catch (IOException e1) {
e1.printStackTrace();
}
for (File f : files) {
System.out.println("merging: " + f.getName());
FileInputStream fis;
try {
fis = new FileInputStream(f);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
while ((aLine = in.readLine()) != null) {
out.write(aLine);
out.newLine();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void stringSearch(String args[]) {
try {
String stringSearch = "test";
BufferedReader bf = new BufferedReader(new FileReader("C:/Users/me/Desktop/merged.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file");
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
}
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
It's because you are searching for the word once per line in your while loop. Each iteration of the loop takes you to the next line of the file because you are calling bf.readLine(). Try something like the following. You may have to tweak it but this should get you close.
while (( line = bf.readLine()) != null){
linecount++;
int indexfound = line.indexOf(stringSearch);
while(indexfound > -1)
{
System.out.println(stringSearch + " was found at position " + indexfound + " on line " + linecount);
System.out.println(line);
indexfound = line.indexOf(stringSearch, indexfound);
}
}
I am trying to parse the text from a file that reads "This is a test. This is a simple test." I need to parse it so I can compare it to another file which is a dictionary. This is apart of a spell check program. I am having troubles implementing a r.readline and r.split methods.
String fileName2 = "test.txt";
String line2 = null;
String[] diction2 = new String [100];
try {
// FileReader reads text files in the default encoding.
FileReader fileReader2 =
new FileReader(fileName2);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader2 =
new BufferedReader(fileReader2);
int j=0;
while((line = bufferedReader2.readLine()) != null) {
//System.out.println(line);
diction2[j]=line;
System.out.println(diction2[j]);
j++;
//r.readline(line);
//delimiter
//r.split
//need to parse line to get each individual word out and compare to dictionary
}
// Always close files.
bufferedReader2.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
Edit:
when you do:
for(String word : words){
//Do some action
}
it means that it will take each string inside the "words" array, one by one, store it inside "word" and execute the "Do some action" for it.
it is the same as writing:
for(int i = 0; i < words.length; i++){
String word = words[i];
//Do something
}
End of edit.
As here:
while((line = bufferedReader2.readLine()) != null) {
You are already reading the line, can't you just do:
String fileName2 = "test.txt";
String line = null;
String[] diction2 = new String [100];
try {
// FileReader reads text files in the default encoding.
FileReader fileReader2 =
new FileReader(fileName2);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader2 =
new BufferedReader(fileReader2);
int j=0;
while((line = bufferedReader2.readLine()) != null) {
//System.out.println(line);
diction2[j]=line;
System.out.println(diction2[j]);
j++;
//There you get the list of all the words in the line
String[] words = line.split(" ");
for(String word : words){
//Check your word here
}
}
// Always close files.
bufferedReader2.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
First, I output the content of the file, here is my code. And then, I will do some string work to edit each line. What if I what to save the changes, how to do it? Can I do it without creating a tmp file?
String executeThis = "cat" + " " + "/var/lib/iscsi/nodes/"
+ iscsiInfo.selectedTargets2.get(i) + "/" + myString + "/default";
String inputThis = "";
Process process = ServerHelper.callProcessWithInput(executeThis, inputThis);
try {
logger.debug("stdOutput for editing targets credential:");
BufferedReader stdOutput = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String s = null;
while ((s = stdOutput.readLine()) != null) {
logger.info("The content is########################"+s)
// do something to edit each line and update the file
}
} catch (IOException e) {
logger.fatal(e);
}
The following steps could achieve what you are looking for.
Instantiate a FileWriter object to create a tmp file.
FileWriter fw = new FileWriter("tmp");
Read line by line from the source file.
Modify this line (string object) in memory.
Write out this string in the tmp file.
fw.write(line);
Close the file handles.
Rename the tmp file to the source file name.
sourceFile.renameTo(targetFile);
This question has been answered here. I repeat the answer.
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
String line;String input = "";
while ((line = file.readLine()) != null) input += line + '\n';
System.out.println(input); // check that it's inputted right
// this if structure determines whether or not to replace "0" or "1"
if (Integer.parseInt(type) == 0) {
input = input.replace(replaceWith + "1", replaceWith + "0");
}
else if (Integer.parseInt(type) == 1) {
input = input.replace(replaceWith + "0", replaceWith + "1");
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input);
// write the new String with the replaced line OVER the same file
FileOutputStream File = new FileOutputStream("notes.txt");
File.write(input.getBytes());
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
public static void main(String[] args) {
replaceSelected("Do the dishes","1");
}
I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I am getting a really long string as the response of the web service I am collecting it in the using the StringBuilder but I am unable to obtain the full value I also used StringBuffer but had no success.
Here is the code I am using:
private static String read(InputStream in ) throws IOException {
//StringBuilder sb = new StringBuilder(1000);
StringBuffer sb = new StringBuffer();
String s = "";
BufferedReader r = new BufferedReader(new InputStreamReader( in ), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
s += line;
} in .close();
System.out.println("Response from Input Stream Reader >>>" + sb.toString());
System.out.println("Response from Input S >>>>>>>>>>>>" + s);
return sb.toString();
}
Any help is appreciated.
You can also split the string in array of strings in order to see all of them
String delimiter = "put a delimiter here e.g.: \n";
String[] datas=sb.toString().split(delimiter);
for(String string datas){
System.out.println("Response from Input S >>>>>>>>>>>>" + string);
}
The String may not print entirely to the console, but it is actually there. Save it to a file in order to see it.
I do not think that your input is too big for a String, but only not shown to the console because it doesn't accept too long lines. Anyways, here is the solution for a really huge input as characters:
private static String[] readHugeStream(InputStream in) throws IOException {
LinkedList<String> dataList = new LinkedList<>();
boolean finished = false;
//
BufferedReader r = new BufferedReader(new InputStreamReader(in), 0xFFFFFF);
String line = r.readLine();
while (!finished) {
int lengthRead = 0;
StringBuilder sb = new StringBuilder();
while (!finished) {
line = r.readLine();
if (line == null) {
finished = true;
} else {
lengthRead += line.length();
if (lengthRead == Integer.MAX_VALUE) {
break;
}
sb.append(line);
}
}
if (sb.length() != 0) {
dataList.add(sb.toString());
}
}
in.close();
String[] data = dataList.toArray(new String[]{});
///
return data;
}
public static void main(String[] args) {
try {
String[] data = readHugeStream(new FileInputStream("<big file>"));
} catch (IOException ex) {
Logger.getLogger(StackoverflowStringLong.class.getName()).log(Level.SEVERE, null, ex);
} catch (OutOfMemoryError ex) {
System.out.println("out of memory...");
}
}
System.out.println() does not print all the characters , it can display only limited number of characters in console. You can create a file in SD card and copy the string there as a text document to check your exact response.
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Responsefromserver");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, "response.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(totalResponse);
writer.flush();
writer.close();
}
catch(IOException e)
{
System.out.println("Error:::::::::::::"+e.getMessage());
throw e;
}