java program to read all text and eliminating whitespace and line - java

i want to write a java program to read all the text from a file but without whitespace and lines..suppose given below is all text from a file now i want to read this text and copy it to other file
var provinfo={"cdn":"//bluehost-
cdn.com","domain":"xyz.com","name":"xyz","phone":["(888) 401-4678","(801)
765-9400"],"code":"bh"};
provinfo.cdn = location.protocol + provinfo.cdn;
such that the resultant text in new file is like
varprovinfo{"cdn":"//bluehostcdn.com","domain":"xyz.com","name":"xyz","phone["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;
as you can see the text is merged into single line by eliminating whitespace and lines. Thats what i want.
scanner = new Scanner(new File("D://actual.txt"));
String a = scanner.useDelimiter("\\Z").next();
String b= a.replaceAll(" ", "");
String c = b.replaceAll("[\\r\\n]+\\s+", "");
System.out.println(c);
I used this code for writing on console but using the same with fileouputstream does not working?

To eliminate the whitespace there is a very useful and overlooked function
yourString.trim()
However, it wont elimante the lines.

Try this,
Scanner scanner = new Scanner(file);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext())
{
stringBuilder.append(scanner.next().replaceAll("\\s", "").replaceAll("\n", ""));
}
System.out.println(stringBuilder.toString());

This is working absolutely fine !!! with your above program.
File outputFile = new File("output.txt");
outputFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
fileOutputStream.write(c.getBytes());
fileOutputStream.close();
// read again from disk to make sure
Scanner scanner1 = new Scanner(new File(outputFile.getAbsolutePath()));
System.out.println(scanner1.next());
output :
varprovinfo={"cdn":"//bluehost-cdn.com","domain":"xyz.com","name":"xyz","phone":["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;

Related

Java delete lines in a file? [duplicate]

This question already has answers here:
Find a line in a file and remove it
(17 answers)
Removing Nth line of File with BufferedReader/BufferedWriter
(1 answer)
Closed 2 years ago.
I have a text file that will have repeated lines of the following information (without bullet points):
Code: 12345
john.doe#gmail.com
10935710517038750
In each "set", the numbers would be different as well as the email address. This is just an example.
What I want to do is scan through the text file, fine the line with the specific code I am searching for, then delete that code, email, and number line. Like, the line with the code in it as well as the next two lines.
I cannot, for the life of me, figure out how to do this. I learned how to replace these lines with something else, but I would like to erase them completely, preferably without having to make a brand new text file every single time, unless there is a way to make the new text file with the deleted lines, and replace the old file with this new one.
Here is the relevant code I have, in segments. The code replaces all lines matching the oldLine variable with an empty line. That isn't what I want, but I can't figure it out otherwise. I had gotten most of this code from an example elsewhere.
//Instantiating the File class
String filePath = "C:\\\\Users\\\\taylo\\\\Astronomy\\\\Which Bright Stars Are Visible\\\\StoreVerificationCodes.txt";
//Instantiating the Scanner class to read the file
Scanner sc = new Scanner(new File(filePath));
//instantiating the StringBuffer class
StringBuffer buffer = new StringBuffer();
//Reading lines of the file and appending them to StringBuffer
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
System.out.println("Contents of the file: "+fileContents);
//closing the Scanner object
sc.close();
String oldLine = "Code: 12345";
String newLine = "";
//Replacing the old line with new line
fileContents = fileContents.replaceAll(oldLine, newLine);
//instantiating the FileWriter class
FileWriter writer = new FileWriter(filePath);
System.out.println("");
System.out.println("new data: "+fileContents);
writer.append(fileContents);
writer.flush();
writer.close();
Well, I think, what you are looking for is substring method. I believe there would be some reason why you have this requirement where you just have the code and you have to delete the next two lines of that set also. Please have a look at below code. It should work, given that the structure of your file is fixed and not going to change.
String filePath = "C:/Users/taylo/Astronomy/Which Bright Stars Are Visible/StoreVerificationCodes.txt";
//Instantiating the Scanner class to read the file
Scanner sc = new Scanner(new File(filePath));
//instantiating the StringBuffer class
StringBuffer buffer = new StringBuffer();
//Reading lines of the file and appending them to StringBuffer
while (sc.hasNextLine()) {
buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
System.out.println("Contents of the file: "+fileContents);
//closing the Scanner object
sc.close();
String oldLine = "Code: 789678";
String newLine = "";
// My changes starts here.............
String codePattern = "Code:"; // A fixed pattern
int firstIndex = fileContents.indexOf(oldLine); // To get the index of code you looking for.
int nextIndex= fileContents.indexOf(codePattern, firstIndex+1);
if(nextIndex != -1) {
nextIndex = fileContents.indexOf(codePattern, firstIndex+1) -5;
fileContents = fileContents.substring(0, firstIndex) + fileContents.substring(nextIndex+3);
}
else
fileContents = fileContents.substring(0, firstIndex);
// My changes done here.............
//fileContents = fileContents.replaceAll(oldLine, newLine); //No need
FileWriter writer = new FileWriter(filePath);
System.out.println("");
System.out.println("new data: "+fileContents);
writer.append(fileContents);
writer.flush();
writer.close();

Is there a way for Java Scanner to include '\n' when it is reading lines?

Is there any way for java.util.Scanner to include the newline escape character when reading from a file?
This is my code:
File myFile = new File("file.txt");
Scanner myReader = new Scanner(myFile);
String content = "";
while(myReader.hasNextLine()) {
content += myReader.nextLine();
}
System.out.println(content);
myReader.close();
When it reads from the file, it doesn't include '\n' or any new lines. Does anyone know how to do this?
Thanks
When it reads from the file, it doesn't include '\n' or any new lines.
Does anyone know how to do this?
You can add the new line explicitly as follows:
while(myReader.hasNextLine()) {
content += myReader.nextLine() + "\n";
}
I also recommend you use StringBuilder instead of String for appending in a loop.
StringBuilder content = new StringBuilder();
while (myReader.hasNextLine()) {
content.append(myReader.nextLine()).append(System.lineSeparator());
// or the following
// content.append(myReader.nextLine()).append('\n');
}
Check StringBuilder vs String concatenation in toString() in Java to learn more about it.
If you you just want to read in lines and the line terminator you can do it by changing the behavior of Scanner.next(). If you run the following it will take in the line and the new line terminator as one unit.
\\z is a regex directive that says to include the line terminator.
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z");
for (int i = 0; i < 5; i++) {
String line = scan.next();
System.out.println(line + "on next line");
}
To read from a file, try this.
try {
Scanner scan = new Scanner(new File("f:/Datafile.txt"));
scan.useDelimiter("\\z");
while (scan.hasNextLine()) {
String line = scan.next();
System.out.print(line);
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

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.

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.

Keyboard input with accented characters: Java

I'm having trouble correctly receiving keyboard input in Java when it has accented characters. For example, I'm trying to input something like "présenter" but it comes in as "pr?senter". I'm not sure how to fix this - I've been trying to use ISO-8859-1 encoding but I still can't get it. Here's part of my code:
Scanner scan = new Scanner(new InputStreamReader(
System.in, Charset.forName("ISO-8859-1")));
I also tried using UTF-8 but I have the same problem. Not sure what else to do! Thanks so much!!
Are you trying to output the read char sequence to console? If so, then it's wrong. Console is not able to show accented characters as well as UTF-8 encoded characters. Just try to write your input to the file (as UTF-8) and check the file then.
The following code produces the correct result:
String charset = "ISO-8859-1";
Scanner scan = new Scanner(System.in, charset);
System.out.print("Enter your text line: ");
String line = scan.next();
System.out.println("Your input: " + line);
File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(line.getBytes(charset));
fos.close();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String readLine = br.readLine();
System.out.println("Your input (loaded from file): " + readLine);
br.close();
fr.close();
The output is:
Enter your text line: présenter
Your input: présenter
Your input (loaded from file): présenter
The file content is correct. The wrong characters by "Your input" are because of local console settings, but the value in the file is correct.

Categories

Resources