I'm trying to write a program for this question: "Write a program that will ask a string and a file name from the user and then removes all the occurrences of that string from that text file."
This is what I have so far:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class RemoveText {
public static void main(String[] args){
//creates a scanner to read the user's file name
Scanner input = new Scanner(System.in);
System.out.println("Enter a file name: ");
String fileName = input.nextLine();
java.io.File file = new java.io.File(fileName);
java.io.File newFile = new java.io.File(fileName);
Scanner stringToRemove = new Scanner(System.in);
System.out.println("Enter a string you wish to remove: ");
String s1 = stringToRemove.nextLine();
//creating input and output files
try {
Scanner inputFile = new Scanner(file);
//reads data from a file
while(inputFile.hasNext()) {
s1 += inputFile.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//supposed to replace each instance of the user input string
//but instead deletes everything on the file and i don't know why
String s2 = s1.replaceAll(s1, "");
try {
PrintWriter output = new PrintWriter(newFile);
output.write(s2);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//closing various scanners
input.close();
stringToRemove.close();
}
}
But for some reason, instead of replacing the string with whitespace, the entire text file becomes empty. What am I doing wrong?
Edit: Okay, so I took everyone's advice and managed to fix the variable problem by introducing a third String variable and using more descriptive variable names.
Scanner s1 = new Scanner(System.in);
String stringToRemove = s1.nextLine();
String fileContents = null;
try {
//stuff here
while (inputFile.hasNextLine()) {
fileContents += inputFile.nextLine();
} catch { //more stuff }
String outputContent = fileContents.replaceAll(stringToRemove, "");
My issue now is that the beginning of the new file starts with "null" before relaying the new content.
String s2 = s1.replaceAll(s1, "");
the first parameter of replaceAll method is what you are looking for to replace, and you are looking for s1, you are saying with this code clean all s1 content...
Where you went wrong is that you appended the file content to s1 which is the string you want to remove.
Try introduce s3 and then do
s2 = s3.replaceAll(s1, "");
Related
I'm creating a program, where i must read special text files. I have a problem with a reading text from specified word to another specified word(not including these words). Is using a scanner a good approach to this problem?
I mean something like that:
"text1
text2
text3
text4
text5"
And i want to get from it String with "text2 text3 text4".
I tried using useDelimeter but I can not figure out how to apply it to this case. I created a method that allows me to skip lines, but this is not a good solution in the long run and it will work for only one specified file.
Here is one of my methods I want to make it here
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
//skipLine(sc, 8);
sc.useDelimiter("R");
String sentence = sc.next();
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
How about something like this:
private String readFile3(File file) {
try {
Scanner sc = new Scanner(file);
boolean save = false;
String sentence = "";
String temp = "";
while (sc.hasNextLine()) {
temp = sc.nextLine();
if (sentence.contains("text1")) {
if (!save) {
temp = sc.nextLine();
}
save = true;
}
if (sentence.contains("text5")) {
save = false;
}
if (save) {
sentence = sentence + temp;
}
}
// skipLine(sc, 8);
//sc.useDelimiter("R");
sentence = sentence.replaceAll("\\n", "");
textAreaD.setText(sentence);
} catch (FileNotFoundException e) {
System.out.println("No file");
}
return null;
}
Should read out all strings between "text1" and "text5". Maybe you have to do some more formatting and check if "text1" occurs more than one time, if you want to save that too, but i hope it helps you.
I am working on a project that involves asking a user for their zip code. Using the zip code provided the program should loop through a .csv file to determine what city they live in. I can read the information in the .csv file but I have no idea how to loop through it to find a specific piece of information.
import java.util.Scanner;
import java.io.*;
public class DetermineCity {
public static void main(String[] args) throws IOException {
String zip = "99820,AK,ANGOON";
Scanner keyboard = new Scanner(System.in);
System.out.println("enter then name of a file");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is ");
System.out.println(line);
inputFile.close();
}
}
Use Scanner.hasNext() method to loop
String Details="";
int ZipCodeIndex=0;
String ZipCode = "10230"
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext()){
String x=inputFile.nextLine();
String[] arr=x.split(",");
if(ZipCode.equals(arr[ZipCodeIndex]))
{
Details=x;
break;
}
}
This assumes the format of your file is of the form "2301,Suburb, City, Country"
the .nextLine() function returns a String of the next line, however return null if their isn't a line. So using a while loop you can go through your file and store each line in a string.
Then using .split() method you would break this string using a delimiter ",". This would be stored in an array.
Then compare the user zip code with the first value of the array. If they match then you have an array with the city and other information. Then a break statement as you have found the city.
String suburb;
String[] lineArray;
String line = null;
while((line = inputFile.nextLine()) != null){
lineArray[] = line.split(",");
if(lineArray[0] == zipCodeString){
suburb = lineArray[1];
break;
}
}
Here is my txt file look like.
admin 12345
funny 123
loop 12390
Hi guys. I am trying to replace particular text in my txt file. For example, I want to replace admin's 12345 with something else that I key in in my input2, it means I want to replace the String(pass) that I find out from txt file through scanner. If I use bufferedwritter, the whole content is going to rewrite..How o solve this problem. I am newbie of programming, kindly need you all help.
login.addActionListener(this);
public void actionPerformed(ActionEvent e) {
String inputUser = input1.getText();
String inputPass = input2.getText();
File loginf = new File("oop.txt");
try{
if(e.getSource()==login)
{
Scanner read = new Scanner(new File("oop.txt"));
boolean loginTry = true;
while(read.hasNext())
{
String user = read.next();
String pass = read.next();
if(inputUser.equals(user) && inputPass.equals(pass)){
loginTry=false;
break;
}
}
if(!loginTry)
{
JOptionPane.showMessageDialog(this,"Login Successful");
}
Here is a simple example on how to do what you want!
//Replace a line or word in a file
import java.io.*;
public class BTest
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
OUTPUT
file.txt
I drink Java
I sleep Java
This is test string 1
This is test string 20000
I did both because the way your txt file is you have more than just a word, you have an ID number of some sorts right next to your users login information. So i would use change line!
Please consider the following code. I'm not very familiar with StringBuilders or reading/writing data. I need to:
1.) Open source file
2.) Grab words and check for old string, if an old string, then append new string
3.) Use PrintWriter and Close. I am revising the following code below:
import java.io.*;
import java.util.*;
public class ReplaceText {
public static void main(String[] args) throws Exception {
// Check command line parameter usage
if (args.length != 4) {
System.out.println(
"Usage: java ReplaceText sourceFile targetFile oldStr newStr");
System.exit(1);
}
// Check if source file exists
File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(2);
}
// Check if target file exists
File targetFile = new File(args[1]);
if (targetFile.exists()) {
System.out.println("Target file " + args[1] + " already exists");
System.exit(3);
}
// Create input and output files
Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(targetFile);
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[2], args[3]);
output.println(s2);
}
input.close();
output.close();
}
}
I'd also like to ask the user for the source file, old string, and new string at run time instead of using command line arguments.
I know I still need to incorporate StringBuilder. Here is what I have so far:
public class ReplaceText {
public static void main(String [] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("What is the source file");
java.io.File file = new java.io.File(scan.next());
System.out.println("Enter old line");
String oldLine = scan.nextLine();
System.out.println("Enter new line");
String newLine = scan.nextLine();
//scan.exit;
/** Read one line at a time, append, replace oldLine with
* newLine using a loop */
//Scanner scan2 = new Scanner(file);
//PrintWriter that replaces file
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(file);
output.close();
}
}
I dont have alot of experience working with files. I have a file. I have written the following to the file
Test 112
help 456
news 456
Friendly 554
fileOUT.write("Test 112\r\n");//this is a example of how I entered the data.
Now I am trying to search in the file for the word news and display all the content that is in that line that contains the word news.
This is what I have attempted.
if(fileIN.next().contains("news")){
System.out.println("kkk");
}
This does not work. The folowing does find a word news because it displays KKK but I dont have an Idea how to display only the line that it news was found in.
while(fileIN.hasNext()){
if(fileIN.next().contains("Play")){
System.out.println("kkk");
}
}
What must be displayed is news 456.
Thank You
You want to call fileIN.nextLine().contains("news")
Try using the Scanner class if you are not already. It does a wonderful job of splitting input from a stream by some delineator (in this case the new line character.)
Here's a simple code example:
String pathToFile = "data.txt";
String textToSearchFor = "news";
Scanner scanner = new Scanner(pathToFile);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains(textToSearchFor)){
System.out.println(line);
}
}
scanner.close();
And here's an advanced code example that does much more than you asked. Enjoy!
//Search file for an array of strings. Ignores case if caseSensitive is false.
public void searchFile(String file, boolean caseSensitive, String...textToSearchFor){
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String originalLine = scanner.nextLine();
String line = originalLine;
if(!caseSensitive) line = line.toLowerCase();
for(String searchText : textToSearchFor){
if(!caseSensitive) searchText = searchText.toLowerCase();
if(line.contains(searchText)){
System.out.println(originalLine);
break;
}
}
}
scanner.close();
}
//usage
searchFile("data.txt",true,"news","Test","bob");
searchFile("data.txt",true,new String[]{"test","News"});
you can try this code...:D
String s = null;
File file = new File(path);
BufferedReader in;
try {
in = new BufferedReader(new FileReader(file));
while (in.ready()) {
s = in.readLine();
if(s.contains("news")){
//print something
}
}
in.close();
} catch (Exception e) {
}