Having a bit of a headache trying to parse a text file correctly, it's a pull from mysql database but the data needs to be changed a fair bit before it can be inserted again.
My program is taking a .txt file and parsing it to produce a .txt file, which is simple enough.
The issue is that it is not splitting the file correctly. The file looks as follows (the middle field of each looks strange because I've changed it to random letters to hide the real data):
(92,'xxxname',4013),(93,'sss-xxx',4047),(94,'xxx-sss',3841),(95,'ssss',2593),(96,'ssss-sss',2587),(97,'Bes-sss',2589),
I want to split it so that it produces a file like:
(92, 'xxxname',4013),
(93, 'sss-xxx', 4047),
(94, 'xxx-sss', 3841),
And so on...
Current code for parsing is as follows:
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String line = scanner.next();
String[] lines = line.split(Pattern.quote("),"));
for (String aLine : lines) {
logLine(aLine);
}
}
}
public static void logLine(String message) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true),
true);
out.println(message);
out.close();
}
Currently the output I'm getting is roughly on track but more split up than it should be, and of course the split method is removing the ")," which is unnecessary.
Sample of the current output:
*(1,'Vdddd
Cfffff',1989
(2,'Wdd',3710
(3,'Wfffff
Hffffff
Limited-TLC',3901
(4,'ffffffun88',2714
(5,'ffffff8',1135
(6,'gfgg8*
Been playing around for a while and have done a good bit of searching here and elsewhere but out of ideas, any help would be greatly appreciated.
You can use String.replace. There's also no need to create multiple PrintWriters and close the stream every time.
public void parseSQL(File file) throws IOException {
Scanner scanner = new Scanner(file);
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
while (scanner.hasNext()) {
String line = scanner.next();
out.println(line.replace("),", ")," + System.lineSeparator()));
}
out.close();
}
The answer is simple, this line:
String line = scanner.next();
Should be:
String line = scanner.nextLine();
Thanks for your attempts folks sorry for being dumb
Related
I'm writing a small Java code to modify a txt.
Here's what im trying to work with, we have this long file to be imported on our accountability system, but it's generated with some information that really doesn't matter to the accountant and just makes his work harder.
The file comes in lines like this:
00;1;1;22012018;"1779";"C";0;0;139084;0;2;0;"RECEBTO TITULO 001/000664/02 - EDGAR ROSA DA TRINDADE";7;19247028000;4561000150;1;
And what im trying to do is to just remove the 001/ and the /02 in the first line.
And the output would be like(2000+ lines):
00;1;1;22012018;"1779";"C";0;0;139084;0;2;0;"RECEBTO TITULO 000664 - EDGAR ROSA DA TRINDADE";7;19247028000;4561000150;1;
it isn't a fixed value so a cant just .replaceall() on the file. It varies from 2 to even 8 digits on both sides or spacings before/after the bar. like so 0000123 / 123.
My questions are.
What kind of function or replacing parameter should i use to include all of the diversity of data it the files?
Just read the file line by line and remove the char sequence with java regex, then write them to a new file.
public class Example {
private static final String PREFIX = "\\d+/";
private static final String SUFFIX = "/.*-";
public static void main(String[] args) throws IOException{
File target = new File("target.txt");
FileWriter fileWriter = new FileWriter(target);
File source = new File("source.txt");
FileReader fileReader = new FileReader(source);
try {
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
fileWriter.write(line.replaceFirst(PREFIX, "").replaceFirst(SUFFIX, " -"));
fileWriter.write("\r\n");
}
} finally {
fileReader.close();
fileWriter.close();
}
}
}
So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
String save = new String();
while(sc.hasNextLine())
{
save=sc.nextLine();
}
byte buf[]=save.getBytes();
FileOutputStream fos = new FileOutputStream(f);
for(int i=0;i<buf.length;i++)
fos.write(buf[i]);
if(fos != null)
{
fos.flush();
fos.close();
}
}
If anyone has a way to fix the code or even a better idea for saving please let me know, thanks
You are replacing save value in every single nextLine.
Change this line:
save = sc.nextLine();
to this one:
save += sc.nextLine();
Also, it's better to use a FileWriter when you are writing String to a file.
And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
Look at code included below:
public static void main (String[] args) throws Exception
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine())
{
builder.append(sc.nextLine() + "\n");
}
String save = builder.toString();
FileWriter writer = new FileWriter(f);
writer.write(save);
writer.close();
}
Also close() implicitly calls flush().
I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.
import java.io.*;
import java.util.*;
public class Readfilm {
public static void main(String[] args) throws IOException {
ArrayList films = new ArrayList();
File file = new File("filmList.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext())
{
String filmName = scanner.next();
System.out.println(filmName);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}}
Above is the code I'm currently attempting to use, it compiles fine, then I get a runtime error of:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Readfilm.main(Readfilm.java:15)
I've googled the error and not had anything that helped (I only googled the first 3 lines of the error)
Basically, the program I'm writing is part of a bigger program. This part is to get information from a text file which is written like this:
Film one / 1.5
Film two / 1.3
Film Three / 2.1
Film Four / 4.0
with the text being the film title, and the float being the duration of the film (which will have 20 minutes added to it (For adverts) and then will be rounded up to the nearest int)
Moving on, the program is then to put the information in an array so it can be accessed & modified easily from the program, and then written back to the file.
My issues are:
I get a run time error currently, not a clue how to fix? (at the moment I'm just trying to read each line, and store it in an array, as a base to the rest of the program) Can anyone point me in the right direction?
I have no idea how to have a split at "/" I think it's something like .split("/")?
Any help would be greatly appreciated!
Zack.
Your code is working but it reads just one line .You can use bufferedReader here is an example import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And here is an split example class StringSplitExample {
public static void main(String[] args) {
String st = "Hello_World";
String str[] = st.split("_");
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}
}
I wouldn't use a Scanner, that's for tokenizing (you get one word or symbol at a time). You probably just want to use a BufferedReader which has a readLine method, then use line.split("/") as you suggest to split it into two parts.
Lazy solution :
Scanner scan = ..;
scan.nextLine();
I am trying to write a String(lengthy but wrapped), which is from JTextArea. When the string printed to console, formatting is same as it was in Text Area, but when I write them to file using BufferedWriter, it is writing that String in single line.
Following snippet can reproduce it:
public class BufferedWriterTest {
public static void main(String[] args) throws IOException {
String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
System.out.println(string);
File file = new File("C:/Users/User/Desktop/text.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(string);
bufferedWriter.close();
}
}
What went wrong? How to resolve this? Thanks for any help!
Text from a JTextArea will have \n characters for newlines, regardless of the platform it is running on. You will want to replace those characters with the platform-specific newline as you write it to the file (for Windows, this is \r\n, as others have mentioned).
I think the best way to do that is to wrap the text into a BufferedReader, which can be used to iterate over the lines, and then use a PrintWriter to write each line out to a file using the platform-specific newline. There is a shorter solution involving string.replace(...) (see comment by Unbeli), but it is slower and requires more memory.
Here is my solution - now made even simpler thanks to new features in Java 8:
public static void main(String[] args) throws IOException {
String string = "This is lengthy string that contains many words. So\nI am wrapping it.";
System.out.println(string);
File file = new File("C:/Users/User/Desktop/text.txt");
writeToFile(string, file);
}
private static void writeToFile(String string, File file) throws IOException {
try (
BufferedReader reader = new BufferedReader(new StringReader(string));
PrintWriter writer = new PrintWriter(new FileWriter(file));
) {
reader.lines().forEach(line -> writer.println(line));
}
}
Please see the following question on how to appropriately handle newlines.
How do I get a platform-dependent new line character?
Basically you want to use
String newLineChar = System.getProperty("line.separator");
and then use the newLineChar instead of "\n"
I just ran your program, and adding a carriage return (\r) before your newline (\n) did the trick for me.
If you want to get a system independent line separator, one can be found in the system propery line.separator
String separator = System.getProperty("line.separator");
String string = "This is lengthy string that contains many words. So" + separator
+ "I am wrapping it.";
If you wish to keep the carriage return characters from a Java string into a file. Just replace each break line character (which is recognized in java as: \n) as per the following statement:
TempHtml = TempHtml.replaceAll("\n", "\r\n");
Here is an code example,
// When Execute button is pressed
String TempHtml = textArea.getText();
TempHtml = TempHtml.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/temp.html"))) {
out.print(TempHtml);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(TempHtml);
If you are using a BufferedWriter, you could also use the .newline() method to re-add the newline based on your platform.
See this related question: Strings written to file do not preserve line breaks