Trying to get Scanner to scan entire file - java

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.

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();
}

Sentinel value at the end of a file?

I read in the contents of my File likewise:
List<String> list = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(file));
while( scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
At the EOF I want to send the String "###" to act as a Sentinel Value to know that its the end. However, I do not have "###" in the File that is being read into. Any suggestions on how I might approach this?
List<String> list = new ArrayList();
Scanner scanner = new Scanner(new FileInputStream(file));
while( scanner.hasNextLine())
{
list.add(scanner.nextLine());
}
list.add("###");
Just add the line list.add("###"); after your while loop.
You'll know you've read the entire file in by then, so just add the constant string. You may want to consider separating out the string for readability with something like:
public static final String SENTINEL = "###";

java program to read all text and eliminating whitespace and line

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;

Java Scanner multiple delimiter

I know this is a very asked question but I can't find and apropiate answer for my problem. Thing is I have to program and aplication that reads from a .TXT file like this
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
My question is how what can I do to tell Java that I want String before : in one ArrayList and Strings after : in another ArrayList?? I guess It's using delimeter method but I don't know how use it in this case.
Sorry for my poor english, I've to improve It i guess. Thanks
use split function of java.
steps:
Declare two arrayList. l1 and l2;
read each line.
split each line by ":", this will return a array of length 2, array. (as per your input)
l1.add(array[0]) , l2.add(array1)
try yourself, post code if you need help :)
check here for use of split function, though through google you can find many different example
Split the string using ":" as delimiter. Add the odd entries from the result to one list and even to another list.
If your text is like this:
Real:Atelti
Alcorcon:getafe
Barcelona:Sporting
You can achieve what you want by using:
StringBuilder text = new StringBuilder();
Scanner scanner = new Scanner(new FileInputStream(fFileName), encoding); //try utf8 or utf-8 for 'encoding'
try {
while (scanner.hasNextLine()){
String line = scanner.nextLine();
String before = line.split(":")[0];
String after = line.split(":")[1];
//dsw 'before' and 'after' - add them to lists.
}
}
finally{
scanner.close();
}
Scanner scanner = new Scanner(new FileInputStream("YOUR_FILE_PATH"));
List<String> firstList = new ArrayList<String>();
List<String> secondList = new ArrayList<String>();
while(scanner.hasNextLine()) {
String currentLine = scanner.nextLine();
String[] tokenizedString = currentLine.split(":");
firstList.add(tokenizedString[0]);
secondList.add(tokenizedString[1]);
}
scanner.close();
Enumerating firstList and secondList will get you the desired result.
1. Use ":" as delimiter.
2. Then Store them in the String[] using split() function.
3. Try using BufferedReader instead of Scanner.
Eg:
File f = new File("d:\\Mytext.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
ArrayList<String> s1 = new ArrayList<String>();
ArrayList<String> s2 = new ArrayList<String>();
while ((br.readLine())!=null){
String line = br.readLine();
String bf = line.split(":")[0];
String af = line.split(":")[1];
s1.add(bf);
s2.add(af);
}

Categories

Resources