Formatting string to get just words in a column - java

I have a text:
c:\MyMP3s\4 Non Blondes\Bigger!\Faster, More!_Train.mp3
I want to remove form this text these characters: :,\!._
And format the text then like this:
c
MyMP3s
4
Non
Blindes
Bigger
Faster
More
Train
mp3
And write all of this in a file.
Here is what I did:
public static void formatText() throws IOException{
Writer writer = null;
BufferedReader br = new BufferedReader(new FileReader(new File("File.txt")));
String line = "";
while(br.readLine()!=null){
System.out.println("Into the loop");
line = br.readLine();
line = line.replaceAll(":", " ");
line = line.replaceAll(".", " ");
line = line.replaceAll("_", " ");
line = System.lineSeparator();
System.out.println(line);
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Write.txt")));
writer.write(line);
}
And it doesn't work!
The exception:
Into the loop
Exception in thread "main" java.lang.NullPointerException
at Application.formatText(Application.java:25)
at Application.main(Application.java:41)

At the end of your code, you have:
line = System.lineSeperator()
This resets your replacements. Another thing to note is String#replaceAll takes in a regex for the first parameter. So you have to escape any sequences, such as .
String line = "c:\\MyMP3s\\4 Non Blondes\\Bigger!\\Faster, More!_Train.mp3";
System.out.println("Into the loop");
line = line.replaceAll(":\\\\", " ");
line = line.replaceAll("\\.", " ");
line = line.replaceAll("_", " ");
line = line.replaceAll("\\\\", " ");
line = line.replaceAll(" ", System.lineSeparator());
System.out.println(line);
The output is:
Into the loop
c
MyMP3s
4
Non
Blondes
Bigger!
Faster,
More!
Train
mp3

Related

Cannot Read Next Console Line - NoSuchElementException

The idea of this is to take in a console input and use it as the file name for the text file to fill with square root values with various decimal places
however I cannot get it to let me enter anything, it throws a NoSuchElementException and I do not get why? in a previous method, I used this exact code to get the file name as a variable
This is Current Method
private static void FileWritting () throws IOException {
System.out.println("\n6.7.2 Writting Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner2 = new Scanner(System.in);
String filename = Scanner2.nextLine();
FileWriter writehandle = new FileWriter("D:\\Users\\Ali\\Documents\\lab6\\" + filename + ".txt");
BufferedWriter bw = new BufferedWriter(writehandle);
int n = 10;
for(int i=1;i<n;++i)
{
double value = Math.sqrt(i);
String formattedString = String.format("%."+ (i-1) +"f", value);
System.out.println(formattedString);
// bw.write(line);
bw.newLine();
}
bw.close();
writehandle.close();
Scanner2.close();
}
Where This is the previous method
System.out.println("6.7.1 Reading Data");
System.out.println("-----------------------");
System.out.println("Enter the File name");
Scanner Scanner1 = new Scanner(System.in);
String filename = Scanner1.nextLine();
FileReader readhandle = new FileReader("D:\\Users\\Ali\\Documents\\lab6\\"+ filename +".txt");
BufferedReader br = new BufferedReader(readhandle);
String line = br.readLine ();
int count = 0;
while (line != null) {
String []parts = line.split(" ");
for( String w : parts)
{
count++;
}
line = br.readLine();
}
System.out.println("The number of words is: " + count);
br.close();
Scanner1.close();
}
You're calling Scanner#close in your first method. This closes stdin, which makes reading from it impossible. I recommend creating a global variable to hold your scanner and closing it when your program terminates (instead of creating a new one in every method).
More info and a better explanation

Input and Output program

I am trying to get this program to read an input file line by line and then print it to an output file, so for example:
Input file contains:
cookies
cake
ice cream
I want the output file to display this:
Line 1: cookies
Line 2: cake
Line 3: ice cream
I cannot figure out how to do this however, so any help will be appreciated.
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Enter the input file: ");
String name = in.next();
FileReader file = new FileReader(name);
BufferedReader reader = new BufferedReader(file);
String text = "";
String line = reader.readLine();
while(line != null){
text += line;
line = reader.readLine();
}
reader.close();
System.out.print("Enter the output file: ");
String out = in.next();
FileWriter filew = new FileWriter(out);
BufferedWriter buffw = new BufferedWriter(filew);
buffw.write(text);
buffw.close();
System.out.print("File written!");
in.close();
}
}
The problem is with the loop like:
while(line != null){
text += line;
line = reader.readLine();
}
readLine method would eat up the new line character and hence you don't see it in the output file. You need to append a new line character at the end like:
while(line != null){
text += line;
text += '\n';
line = reader.readLine();
}
I would suggest you using StringBuilder instead of string concatenation like:
StringBuilder stringBuilder = ...
while ..
stringBuilder.append(line);
stringBuilder.append('\n');
...
You have to add the end of line character again, because readLine() removes it:
while(line != null){
text += line;
text +="\n";
line = reader.readLine();
}

Reading from file. Android, Java

I have some problem with reading file with Scanner.
My file has a following format:
line 1(basic signs, f.e.: ##%%&&).
line 2(number of lines with data, f.e.: 70)
line 3(some info)
line 4-74(some data in any format with semiColon as a delimiter)
I need to implement loop which started from fourth line and allows me to fill my ListView.
How to solve this problem?
here is part of code:
Scanner read = null;
Pattern b = Pattern.compile(";|\\|\n ");
String BasicSign, NumberOfFields, barcode, name, type, amount, price;
try {
Log.d(LOG_TAG1, "--- Reading from spr: ---");
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath() + File.separator + "myFile1.spr");
read = new Scanner(textFile);
read.useDelimiter(b);
while (read.hasNext()) {
BasicSign = read.next();
NumberOfFields = read.next();
barcode = read.next();
name = read.next();
amount = read.next();
price = read.next();
tvBarcode.setText(barcode123);
tvMyName.setText(name);
tvType.setText(type);
tvPrice.setText(price);
}
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You could process your textfile linewise and skip the first 3 lines and start in the 4th. This is a simple straight forward solution:
BufferedReader br = new BufferedReader(textfile);
br.readLine(); // skip line
br.readLine(); // skip line
br.readLine(); // skip line
String line = br.readLine(); // start in 4th line
while (line !=null) { // end of file not reached
Scanner read = new Scanner(line);
read.useDelimiter(b);
//your while loop and processing
line = br.readLine(); // read line for next iteration
}
br.close();

Read specific data from a .txt file JAVA

I have a problem. I'm trying to read a large .txt file, but I don't need every piece of data that's inside.
My .txt file looks something like this:
8000000 abcdefg hijklmn word word letter
I only need, let's say, the number and the first two text positions: "abcdefg" and "hijklmn" and write it to another file after that. I don't know how to read and write just the data that I need.
Here is my code so far:
BufferedReader br = new BufferedReader(new FileReader("position2.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("position.txt"));
String line;
while ((line = br.readLine())!= null){
if(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n")){
continue;
}else{
//bw.write(line + "\n");
String[] data = line.split(" ");
bw.write(data[0] + " " + data[1] + " " + data[2] + "\n");
}
}
br.close();
bw.close();
}
Can you give me some sugestions ?
Thanks in advance
UPDATE:
My .txt files are a bit weird. Using the code above works great when there is only one single " " between them. My files can have a \t or more spaces, or a \t and some spaces between the words. Ho can I proceed now ?
Depending on the complexity of you data, you have a few options.
If the lines are simple space-separated values like shown, the simplest is to split the text, and write the values you want to keep to the new file:
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(" ");
if (values.length >= 3)
bw.write(values[0] + ' ' + values[1] + ' ' + values[2] + '\n');
}
}
If the values might be more complex, you could use a regular expression:
Pattern p = Pattern.compile("^(\\d+ \\w+ \\w+)");
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
Matcher m = p.matcher(line);
if (m.find())
bw.write(m.group(1) + '\n');
}
}
This ensures that first value is digits only, and second and third values are word-characters only (a-z A-Z _ 0-9).
Assuming all lines of your text file follow the structure you described then you could do this:
Replace FILE_PATH with your actual file path.
public static void main(String[] args) {
try {
Scanner reader = new Scanner(new File("FILE_PATH/myfile.txt"));
PrintWriter writer = new PrintWriter(new File("FILE_PATH/myfile2.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
String[] tokens = line.split(" ");
writer.println(tokens[0] + ", " + tokens[1] + ", " + tokens[2]);
}
writer.close();
reader.close();
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
}
}
You'll get something like:
word0, word1, word2
If your files are really huge (above 50-100 MB maybe GBs) and you are sure that the first word is a number and you need two words after that I would suggest you to read one line and iterate through that string. Stop when you find 3rd space.
String str = readLine();
int num_spaces = 0, cnt = 0;
String arr[] = new String[3];
while(num_spaces < 3){
if(str.charAt(cnt) == ' '){
num_space++;
}
else{
arr[num_space] += str.charAt(cnt);
}
}
If your data is couple of MB only or have a lot of numbers inside, no need to worry about iterating char by char. Just read line by line and split lines then check the words as it is mentioned
else {
String[] res = line.split(" ");
bw.write(res[0] + " " + res[1] + " " + res[2] + "\n"); // the first three words...
}

Line by line input via java console

Please help me to input by line by line via java console. Now i can give input only as one line. How to give multiple inputs in line by line??
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String CurLine = ""; // Line read from standard in
while (!(CurLine.equals("quit"))){
CurLine = in.readLine();
if (!(CurLine.equals("quit"))){
System.out.println("You typed: " + CurLine);
}
}
You need to use Scanner and loop through to ask for multiple times.
For example
Scanner stdin = new Scanner(new BufferedInputStream(System.in));
while (stdin.hasNext()) {
//Get input and do your logic.
}
I'm not sure I understand your question but...
final List<String> inputs = new ArrayList<String>();
final Scanner in = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
System.out.print("> ");
inputs.add(in.next());
}
System.out.println(inputs);
Use the new Console class:
Console console = System.console();
if (console != null) {
Scanner scanner = new Scanner(console.reader());
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Do something with your line
}
}
End the input by pressing ^Z (control-Z) followed by ENTER.
It has one caveat and that is that the console can be null inside an IDE. Try it from the command-line and you should be fine:
java path.to.my.MainClass

Categories

Resources