How to escape the white space in folder name of a file? - java

Consider the source_folder_name as D:\Desktop\test util\config sql
In the code given below the white space in the folder name i.e test util and config sql is not handled properly.
I need to escape those white spaces.
public class SqlToTblCoverter {
private File source_folder = null;
public SqlToTblCoverter(String source_folder_name) {
source_folder = new File(source_folder_name);
}
public void check() {
System.out.println("Source folder"+ source_folder);
}
}
public class test{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
System.out.println("Enter Input Folder Path");
String input=in.next();
SqlToTblCoverter config_migrator = new
SqlToTblCoverter(input);
}
}
On executing the above code the value of source_folder comes is
Source folder: D:\Desktop\test
whereas expected is
Source folder: D:\Desktop\test util\config sql
Please help me out

If you read the documentation of Scanner you will see:
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.
So the problem is your scanner. If you use the newlines as delimiter, everything should work as expected.

Related

Printing a Specified File Exercise Java

Taking a beginners course in Java and I am stuck on one of the exercises. We're meant to print the text within a specific file, which we can find via the file's name which was inputted by a user. In our previous exercise, we learned that
try(Scanner scanner = new Scanner(Paths.get("data.txt")))
would find the text within the file "data.txt", but I am unsure about how to convert this into finding any file name inputted by the user.
More details below.
Exercise: Write a program that asks the user for a string, and then prints the contents of a file with a name matching the string provided. You may assume that the user provides a file name that the program can find.
The exercise template contains the files "data.txt" and "song.txt", which you may use when testing the functionality of your program. The output of the program can be seen below for when a user has entered the string "song.txt". The content that is printed comes from the file "song.txt". Naturally, the program should also work with other filenames, assuming the file can be found.
My code so far is:
import java.nio.file.Paths;
import java.util.Scanner;
public class PrintingASpecifiedFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Which file should have its contents printed?");
String fileName = scanner.nextLine();
//try(Scanner scanner = new Scanner(Paths.get(fileName))) {
try(scanner = Paths.get(fileName)) { // this part of the code is underlined red
while (scanner.hasNextLine()){
String output = scanner.nextLine();
System.out.println(output);
}
}
catch (Exception e){
System.out.println("Error: " + e.getMessage());
}
}
}
I have tried searching how to add a new scanner as that was a suggestion but every time I've tried it gets an error. Also the "try" section is underlined red and cannot seem to figure out why. The underlined red part says variables in try-with-resources are not supported in -source 8
If anyone has tips, I would really appreciate it! Thank you!
You used one Scanner for reading the file path from the console.
You need an other Scanner (or reader alternative) for reading the file.
try (Scanner fileScanner = new Scanner(fileName)) {
try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {

Replace Pattern match with Preferred Text Java

Hey I am trying to replace the a regex pattern in a directory of files and replace with this character 'X'. I started out trying alter one file but that is not working. I cam eup with the following code any help would be appreciated.
My goal is to read all the file content find the regex pattern and replace it.
Also this code is not working it runs but dose nothing to the text file.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DataChange {
public static void main(String[] args) throws IOException {
String absolutePathOne = "C:\\Users\\hoflerj\\Desktop\\After\\test.txt";
String[] files = { "test.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File(absolutePathOne));
FileUtils.writeStringToFile(f, content.replaceAll("2018(.+)", "X"));
}
}
}
File Content inside the file is:
3-MAAAA2017/2/00346
I am trying to have it read through and replace 2017/2/00346 with XXX's
my goal is to do this for like 3 files at one time also.

How to read a file based on string position and store it in variable

I need to read a file, completely and split the strings inside the file and store it in a variable using Java
See below example, my text file contains
devarajan 1000210 08754540275 600019
ramesh 1000210 08754540275 600019
udhay 1000210 08754540275 600019
I tired using string position but it is not working out.
Please find attached sample file as well. Regards
My Code:
public class Program {
public static void main(String[] args) {
String line = "devarajan 1000210 08754540275 600019 ";
String[] words = line.split("\\W+");
for (String word : words) {
System.out.println(word);
}
}
}
Output:
devarajan 1000210 08754540276
My file will contain the list of string 10-10 position will be name 20-30 position will be empid 30-40 will phone number. so while i used the previous snippet i am getting blank spaces "devarajan" " 1000210".. i should avoid that blank spaces.
In turn my code is splitting up as soon as it encounters blank space, instead of position
#Twelve, # Kick : I am getting the output as follows for your snippet
but imagine if i have a space in my name ex: "twelve dollar" instead of "
twelvedollar", then the name will get split and stored in different array position. and that is the reason, i have asked whether it is possible to split the string based on the position
just one way to do it ..
try {
Scanner inFile = new Scanner(new File("myInputFile.txt"));
String[] data;
ArrayList<String[]> arr = new ArrayList<String[]>();
while (inFile.hasNext()) {
data = inFile.nextLine().split("\\s+"); // or split("\t") if using tabs
System.out.println(Arrays.toString(data));
arr.add(data);
}
}
catch (FileNotFoundException fe) {
fe.printStackTrace();
}

extract information separated with pipes from file and save it to another file

considering the following file "sample.txt" as input for a java program which contains the following information:
#1|77|1391436891|1|1|00:1e:58:f4:15:f7|Nexus 4, 4.4, MAKOZ30d
$1|1391436893
?[176.08179, -13.839829, -1.0054213]
%PKKV7|00:7f:28:3f:17:9d|-67|2437
%DC2VJ|f8:e4:fb:a0:06:f8|-71|2412
%VVWSP|00:7f:28:d5:92:65|-71|2462
%SVT8H|f8:e4:fb:8e:d6:9b|-77|2437
%ThreeBestFriends|20:10:7a:14:6a:f7|-66|2452
%2X4C8|00:7f:28:44:23:da|-75|2437
%STDGD|f8:e4:fb:70:86:f4|-82|2462
%DeathStar|00:7f:28:be:c8:94|-84|2412
%Freeinternet|00:1e:58:f4:15:f7|-59|2437
%QB657|00:26:62:b7:16:4b|-88|2462
%375F2|00:26:b8:3e:0a:14|-70|2412
%E1K38|00:26:62:cf:90:37|-81|2412
I'm trying to get an "output.txt" file as following:
00:7f:28:3f:17:9d|-67
f8:e4:fb:a0:06:f8|-71
00:7f:28:d5:92:65|-71
f8:e4:fb:8e:d6:9b|-77
20:10:7a:14:6a:f7|-66
00:7f:28:44:23:da|-75
f8:e4:fb:70:86:f4|-82
00:7f:28:be:c8:94|-84
00:1e:58:f4:15:f7|-59
00:26:62:b7:16:4b|-88
00:26:b8:3e:0a:14|-70
00:26:62:cf:90:37|-81
any recommendations on how to achieve this in java?
The following regular expression will extract this:
\w{2}:\w{2}:\w{2}:\w{2}:\w{2}:\w{2}\W{1}-\d{2}
http://ideone.com/FwpV7z
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String testData = "#1|77|1391436891|1|1|00:1e:58:f4:15:f7|Nexus 4, 4.4, MAKOZ30d $1|1391436893 ?[176.08179, -13.839829, -1.0054213] %PKKV7|00:7f:28:3f:17:9d|-67|2437 %DC2VJ|f8:e4:fb:a0:06:f8|-71|2412 %VVWSP|00:7f:28:d5:92:65|-71|2462 %SVT8H|f8:e4:fb:8e:d6:9b|-77|2437 %ThreeBestFriends|20:10:7a:14:6a:f7|-66|2452 %2X4C8|00:7f:28:44:23:da|-75|2437 %STDGD|f8:e4:fb:70:86:f4|-82|2462 %DeathStar|00:7f:28:be:c8:94|-84|2412 %Freeinternet|00:1e:58:f4:15:f7|-59|2437 %QB657|00:26:62:b7:16:4b|-88|2462 %375F2|00:26:b8:3e:0a:14|-70|2412 %E1K38|00:26:62:cf:90:37|-81|2412";
String regularExpression = "\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}\\W{1}-\\d{2}";
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(testData);
while(matcher.find()) {
System.out.println(matcher.group(0));
}
}
}
output:
00:7f:28:3f:17:9d|-67
f8:e4:fb:a0:06:f8|-71
00:7f:28:d5:92:65|-71
f8:e4:fb:8e:d6:9b|-77
20:10:7a:14:6a:f7|-66
00:7f:28:44:23:da|-75
f8:e4:fb:70:86:f4|-82
If you read the line as a String you can use split to split it up for the pipes.
Here's a good start (might be typo's since I did write it straight in here)
//Read all lines, one line at a time with a simple scanner:
Scanner sc = new Scanner(new File("sample.txt"));
while (sc.hasNextLine()){
String line = sc.nextLine();
//If the line starts with a % do something, else ignore
if (line.charAt(0) == '%'){
int firstPipe = line.indexOf("|");
int secondPipe = line.indexOf("|",firstPipe);
//Now use String.substring() and perhaps a temporary StringBuffer storage followed by, for example, a FileWriter to create the output file

Is there any way to return an entire line of a .txt document?

I'm currently working on a java program that requires you to use several scanners on several txt files to return definitions of names, as well as a few numbers that go along with them about their popularity. Currently, I'm having difficulty returning this data back to the original program.
An example of how the .txt File with the definitions is as follows:
ADAMO m Italian Italian form of ADAM
ADAN mf (no meaning found)
ADANNA f Igbo Means "father's daughter" in Igbo.
ADANNAYA f Igbo Means "her father's daughter" in Igbo.
ADAOIN f Irish Modern form of TAN
My program currently looks like this thus far:
import java.io.*;
import java.util.Scanner;//For reading the file.
public class BabyNamesProject {
//This program will use user input to scan several text documents for information regarding names.
//It will give the popularity of the name in the last few decades, it's meaning, and a Drawing Panel chart with it's popularity.
public static void main(String[] args)
throws FileNotFoundException {
File f = new File("Names.txt");
File g = new File("Meanings.txt");
File h = new File("Names2.txt");
Scanner nameCheck = new Scanner(f);
Scanner meaningCheck = new Scanner(g);
Scanner popularityCheck = new Scanner(h);
Scanner Ask = new Scanner(System.in);
String userName = "";
String upperUserName = "";
String meaning = "";
System.out.println("Hello! This application will allow you to check how popular certain names are compared to others.");
System.out.println(" ");
System.out.println("Please type in your name!");
userName = Ask.next();
upperUserName = userName.toUpperCase();
if (meaningCheck.hasNext(""+ upperUserName))
meaning = meaningCheck.next("" + upperUserName);
System.out.println("" + meaning);
System.out.println("" + userName +"! That's one the rarest cards in all of duel monsters!");
}
}
As you may notice, it's nowhere near finished, but what I can't seem to figure out is how to both search the .txt file, using the uppercase name the user imputs, and how to make it return the entire line. So far, it seems like plenty of searches on here have led me to carriage returns, which I at least understand how they work, but not how to use one. If anyone has time to explain something I could do to solve this, it would be greatly appreciated!
The method is called nextLine():
File f = new File("text.txt");
Scanner s = new Scanner(f);
String line = s.nextLine();
You can use a BufferedReader to read the text file line-by-line and do whatever you please with it.
Have a look here: http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

Categories