I want to edit a text file. this is the original file:
kopfor20 22 22
second line 3
last line 4
I want it to be like this:
new 22 22
second line 3
last line 4
What I have done so far is I stored the txt file to an array after that I replaced "kopfor20" with "new" however I can't seem to store the array back to txt file.
Here is what i have done so far :
public static void main(String[] args) throws IOException {
File f1 = new File("test.txt");
if (!f1.exists()) {
f1.createNewFile();
}
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter("test.txt");
pw.write("kopfor20 22 22\n");
pw.write("second line 3\n");
pw.write("last line");
pw.close();
txttoArray();
arraytoFile();
System.out.println("finished");
}
public static void arraytoFile() {
try {
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter("test.txt");
System.out.println("enter new txt");
Scanner sc = new Scanner(System.in);
String n = sc.next();
System.out.println("Enter old txt to replace ");
String m = sc.next();
String[] textarray = txttoArray();
for (int i = 0; i < textarray.length; i++) {
if (m == textarray[i]) {
System.out.println(textarray[i]);
textarray[i] = n ;
System.out.println(textarray[i]);
}
}
System.out.println("done");
for (int i = 0; i < textarray.length; i++) {
pw.write(n);
}
pw.close();
} catch (Exception e) {
e.printStackTrace();
}}
public static String[] txttoArray(){
try {
int ctr = 0;
Scanner sc = new Scanner(new File("test.txt"));
Scanner s = new Scanner(new File("test.txt"));
while(sc.hasNext()){
ctr++;
sc.next();
}
String[] txtline = new String[ctr];
for (int i = 0; i < ctr; i++) {
txtline[i] = s.next();
}
for (int i = 0; i < txtline.length; i++) {
System.out.print(txtline[i]+"\n");
}
} catch (Exception e) {
System.out.println("er");
}
return null ;
}}
Please see if you can help me regarding this.
As the Files
class makes all effort superfluous, use that:
public static void main(String[] args) throws Exception {
// Assume the file is in the computer's local encoding,
// and specify the path to the file:
Charset charset = Charset.defaultCharset();
Path path = Paths.get("test.txt");
// Read the lines of the file:
List<String> lines = Files.readAllLines(path, charset);
// Change the first line, replacing non-whitespace at the line's start:
String header = lines.get(0);
header = header.replaceFirst("^\\S+", "new");
lines.set(0, header);
// Write the lines to the file:
Files.write(path, lines, charset);
}
On the original code: As arrays are fixed-length in java better use List<String> lines = new ArrayList<>(); list.add("foo");
List<String> lines = new ArrayList<>(); list.add("foo");
for a growing list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.