This question already has answers here:
Writing in the beginning of a text file Java
(6 answers)
Closed 4 years ago.
I have this method that can read everything within a file but i need to be able to first add one whitespace before every new char at the beginning of everyline.
Tried to make it as easy as possible but non of it seem to work.
private static void write() throws IOException {
FileWriter fw = new FileWriter("C:\\Users\\karwa\\Desktop\\HistoryOfProgramming.txt");
for (int i = 0; i < 15; i++) {
fw.write(" ");
}
fw.close();
}
Used bufferedReader aswell that had a whileloop that was reading every line and adding one whitespace for each line but that didn't work either. Ideas?
you have to actualy read the lines and store them, only then can you add whitespace
public static void main(String... args) throws IOException {
File file = new File("test.txt");
Scanner fr = new Scanner(file);
List<String> lines = new ArrayList<>();
while (fr.hasNextLine()) {
lines.add(fr.nextLine());
}
PrintStream fw = new PrintStream(file);
for (String line : lines) {
fw.println(" " + line);
}
fr.close();
fw.close();
}
Read/write the contents to a string
Use replaceAll("\n", "\n ");
Related
So I am creating a program which when called, will have input, go to a file and change the number assigned to the string called. For example:
The file would look like:
stone 0 wood 5 water 2 metal 5
and if "wood" was called, it would go into the file, find wood then send add one to the value to the right of wood, which would only change that value to 6, then saves the file.
I've looked around on the internet but couldn't really find much which is tailored to my specific problem. Its either changing an int to either one or the other, or changing all ints to something.
public class Main {
public static void main(String[] args) {
FileWriter fw;
BufferedReader reader;
StringBuffer ib;
String allBlockAndNull = "stone 0 wood 5 water 2 metal 5";
String strDir = "C:\\Users\\amdro\\Desktop\\test.txt";
File fileDir = new File(strDir);
//creates file it doesn't exist
try {
fw = new FileWriter(fileDir);
fw.write(allBlockAndNull);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {}
}
}
If you could expand from the above, that would be great!
This is a very simple and basic solution to your problem: It consists of reading the file, appending all changes to a string and overwriting the same file with the string.
Create a scanner to read your text file and initialise a new string variable
Scanner s = new Scanner(new File("fileName.txt"));
String line = "";
While there is still a character in the text file, get the word and the number
while(sc.hasNext()){
String word = s.next();
int number = s.nextInt();
Then, inside the while loop, use switch and case to check the word. For example, if word = "wood", append "wood" and the new number, newNumber to line
case "wood":
line += word + " " + newNumber + " ";
break;
The default will be appending the word and the old number, number
default:
line += word + " " + number + " ";
Finally, just create a FileWriter and a BufferedWriter to write line to the text file.
You can't add numbers to a value from a file because all the values are Strings but what you can do is replace the String value
public static void main(String[] args) throws IOException {
File file = new File("file.txt");//The file containing stone 0 wood 5 water 2 metal 5
BufferedReader reader = new BufferedReader(new FileReader(file));
String words = "", list = "";
while ((words = reader.readLine()) != null) {
list += words;
}
reader.close();
Scanner s = new Scanner(file);
if(list.contains("wood")) {
String replacedtext = list.replaceAll("wood 5", "wood 6");
FileWriter writer = new FileWriter("file.txt");
writer.write(replacedtext);
writer.close();
}
}
}
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 4 years ago.
It seems fine but the the content is not write into file with write() method. I ask the user input with JoptionPane and add that data to ArrayList . The data is added , but when I try to output that data into file, it's not write to file.
public class fileArray {
public static void main(String[] args) throws IOException {
ArrayList al = new ArrayList();
File f =new File("notworking.txt");
String names = " ";
while(!names.isEmpty())
{
names=JOptionPane.showInputDialog("EnterName");
if(!names.isEmpty()){
al.add(names);}
}
FileWriter fw = new FileWriter(f.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
int sz= al.size();
for(int i =0;i<sz;i++){
bw.write((String) al.get(i));
System.out.println(al.get(i));
}
}
}
You need to close the writer after you are done with writing.
bw.close();
Either you have to flush or close the buffer afte you write to the file. Better you close the buffer in finally block, make it habit to close the buffer in finally block.
sample code:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close(); // CLOSE
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
This question already has answers here:
Java replace line in a text file
(3 answers)
Closed 7 years ago.
I have this content in a text file :
|0| 1 | 2 |
I want to replace the values between "|" by new one.I tried with this method but it add the new modification after the old one like this:
|0| 1 | 2 |new1|new2|.
instead of :
|0| new1 | new2 |
My code is:
public static void generateReplace(String newfield) throws FileNotFoundException, IOException {
FileArrayProvider rs = new FileArrayProvider();
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C:/aa.txt"), true));
Scanner sc = new Scanner(new File("C:/test.txt"));
// bw.write("|");
while(sc.hasNext()){
String line = sc.nextLine();
String nueva = rs.replace(line,newfield);
bw.write(nueva);
// bw.newLine();
}
bw.write("|");
bw.close();
}
FileArrayProvider is my class and it has Replace method :
public String replace(String a,String newfield){
String str = a;
String toBeReplaced = str.substring(0, a.length());
String resultado = str.replace(toBeReplaced, newfield);
return resultado;
}
You are appending the file thus you do not get your required output, just change the true to false in this line
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/Test/src/com/aa.txt"), false));
FileWriter
public FileWriter(File file,
boolean append)
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of
the file rather than the beginning
FileWriter in java
My answer is I do not understand why are you trying to replace the String in the file from which you are loading the data.
There is a simpler approach to this. Since you are loading all the data to the GUI Text Boxes, You simply take the data from the from the text boxes and format them into a string and write the string to a file. If you are thinking of replacing the data on the same file, then you have to call the delete(Path path) method of the File class and then write the file.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I'm trying to take a series of "scores" from a text file to put into an array and then sort in order, rows of four, and write other methods to get the highest, lowest, average, etc. The println commands are in there but I haven't written the methods yet. I've been working all day and I'm starting to confuse myself, and now I'm getting a NullPointerException error in the main method. Any help?
package arrayops1d;
import java.io.*;
import java.util.*;
public class ArrayOps1D {
static int scores[];
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
BufferedReader reader = new BufferedReader(file);
String scores = "";
String line = reader.readLine();
while (line != null){
scores += line;
line = reader.readLine();
}
System.out.println(scores);
System.out.println(getTotal());
System.out.println(getAverage());
System.out.println(getHighest());
System.out.println(getLowest());
System.out.println(getMedian());
System.out.println(getPosition());
System.out.println(getDeviations);
System.out.println(getStdDev);
}
Here is one way you can read the int values from a file into an array of Integer using a Scanner and a List -
Integer[] scores = null;
File file = new File("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
if (file.exists() && file.canRead()) {
try {
List<Integer> al = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
al.add(scanner.nextInt());
} else {
System.out.println("Not an int: " + scanner.next());
}
}
scores = al.toArray(new Integer[al.size()]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Can't find file: " + file.getPath());
}
if (scores != null) {
System.out.println("Scores Read: " + Arrays.toString(scores));
}
First Issue with your code:
In your file path, Instead using / , you must use \\ or better File.separator if your program wants to be ran in different platform.
If you do not , you will have java.io.FileNotFoundException
You are reading line by line, so you can use split Function and use Integer.paraseInt or Float.parseFloat to convert each splited elements and added to your array
How to use Split in Java
How to convert String to int