How to replace the star {*} in text file with a number [duplicate] - java

This question already has answers here:
replace String with another in java
(7 answers)
Closed 3 years ago.
My contents of text file looks something like this
Synonyms of Fluster:
*panic
*perturb
*disconcert
*confuse
......
Now i wish to replace the * with numbers.Something like this.
output
Synonyms of Fluster:
1)panic
2)perturb
3)disconcert
4)confuse
......
Edit:
Integer count = 1;
File input = new File("C:\\Sample.txt");
File output = new File("C:\\output.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
Writer writer =new FileWriter(output);
while((line=reader.readLine())!=null)
{
if(line.contains("*"))
{
line.replace("*",count.toString() );
writer.write(line);
count++;
}
else
{
writer.write(line);
}
}
This is what i had tried before posting question here..But this doesn't seem to work.
Now can somebody help me out..?

You should write a JAVA program.
Here's something that may get you started (rough code):
BufferedReader br = new BufferedReader(new FileReader(file));
//start reading file line-by-line
while ((line = br.readLine()) != null) {
//replace * with whatever you want
// Use a counter to keep track of lines to give corresponding line number
String val = line.replace("*",counterVar.toString());
}
br.close();
Write back to file using BufferedWriter again, wrap it with PrintWriter if you wish to,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outputfile")));

Try something like this (Untested code):
try{
List<String> lines = Files.readAllLines(fileName, Charset.defaultCharset());
for (int i = 0; i< lines.size(); i++) {
lines.set(i, lines[i].replace("*", String.valueOf(i)));
}
} catch (IOException e) {
e.printStackTrace();
}
...//Then save the file

Related

How to remove line from txt file with buffered reader java [duplicate]

This question already has answers here:
Find a line in a file and remove it
(17 answers)
Closed 5 years ago.
I need to remove lines from txt file a
FileReader fr= new FileReader("Name3.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
br.close();
and I don't know the continue of the code.
You can read all lines and store them in a list. Whilst you're storing all lines, assuming you know the line you want to remove, simply check for the lines you don't want to store, and skip them. Then write the list content to a file.
//This is the file you are reading from/writing to
File file = new File("file.txt");
//Creates a reader for the file
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
//This is your buffer, where you are writing all your lines to
List<String> fileContents = new ArrayList<String>();
//loop through each line
while ((line = br.readLine()) != null) {
//if the line we're on contains the text we don't want to add, skip it
if (line.contains("TEXT_TO_IGNORE")) {
//skip
continue;
}
//if we get here, we assume that we want the text, so add it
fileContents.add(line);
}
//close our reader so we can re-use the file
br.close();
//create a writer
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
//loop through our buffer
for (String s : fileContents) {
//write the line to our file
bw.write(s);
bw.newLine();
}
//close the writer
bw.close();

How to I read and edit txt in a serialised file?

I have an object which is serialised and written to a file.
Before de serialising the file back into an object instance, I want to maliciously edit the txt in the file.
//FILE TAMPER
//Lexical block: Tamper
{
String output = null;
//Lexical block make output
{
LinkedList<String> lls = new LinkedList<String>();
//Lexical block: Reader
{
BufferedReader br = new BufferedReader(new FileReader(fileString));
while (br.ready()) {
String readLine = br.readLine();
lls.add(readLine);
}
br.close();
}
//Lexical block: manipulate
{
//Henry Crapper
final String[] llsToArray = lls.toArray(new String[lls.size()]);
for (int i = 0; i < llsToArray.length; i++) {
String line = llsToArray[i];
if (line.contains("Henry")) {
line = line.replace("Henry",
"Fsekc");
llsToArray[i] = line;
}
if (line.contains("Crapper")) {
line = line.replace("Crapper",
"Dhdhfie");
llsToArray[i] = line;
}
lls = new LinkedList<String>(Arrays.asList(llsToArray));
}
}
//Lexical block: write output
{
StringBuilder sb = new StringBuilder();
for (String string : lls) {
sb.append(string).append('\n');
}
output = sb.toString();
}
}
//Lexical block: Writer
{
BufferedWriter bw = new BufferedWriter(new FileWriter(fileString));
bw.write(output);
bw.close();
}
}
However the edited file isn't correct and has some unusual characters.
//Before
¨Ìsr&Snippets.Parsed.EmployeeSerialization0I
bankBalanceLnametLjava/lang/String;xp•Åt
Henry Crappe
//After
ÔøΩÔøΩsr&Snippets.Parsed.EmployeeSerialization0I
bankBalanceLnametLjava/lang/String;xpÔøΩÔøΩt
Fsekc Dhdhfie
I'm guessing there is some sort of non readable character issue or something?
Answer continued in a new question is here
A file which contains a serialized object instance is a binary file: you should not edit it with a BufferedWriter. Edit it with a RandomAccessFile, for example.
If you are wondering of why, the charset used in a Writer could not map one-to-one with a byte. Saving all the file would change also unexpected positions.

Modifying a file at a specific line in Java

I'm writing a method that will allow me to input a line at a specific point in a file, such as a .txt or .vbs script. The problem I'm having is the writing back part, the output file is blank- not containing the entries of my ArrayList scriptCollection. Here is my test method code;
public void testMethod()throws Exception
{
BufferedReader br = new BufferedReader(new FileReader("C:/Users/jchild/Desktop/PrintScript.vbs"));
int indexNo = 1;
int appendAt=0;
String line;
while((line = br.readLine()) != null)
{
scriptCollection.add(line);
if(line.contains("Add at this point"))
{
System.out.println("Successfully read and compared"); //this is just for test output
appendAt = appendAt + indexNo;
}
indexNo++;
}
br.close();
scriptCollection.add(appendAt++,"Appended here");
System.out.println(scriptCollection.toString()); //this is just for test output
//here's what's causing the problem
FileOutputStream fos = new FileOutputStream("C:/Users/jchild/Desktop/PrintScript.txt");
PrintWriter is = new PrintWriter(fos);
for(String temp : scriptCollection)
{
is.println(temp);
}
scriptCollection.clear();
}
You have to close the streams.

How to set String equal to text in .txt file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
I have a .txt file that I want to save in a String variable. I imported the file with File f = new File("test.txt");. Now I am trying to put the contents of it in a String variable. I can not find a clear explanation for how to do this.
Use a Scanner:
Scanner file = new Scanner(new File("test.txt"));
String contents = file.nextLine();
file.close();
Of course, if your file has multiple lines you can call nextLine multiple times.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}

Reading a text file in java

How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.
I'm a complete noob in Java so sorry if this question is a bit stupid.
Thanks
Try the Scanner class which no one knows about but can do almost anything with text.
To get a reader for a file, use
File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (file), encoding));
... use reader ...
reader.close ();
You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.
Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;
List<String> lines = FileUtils.readLines(new File("untitled.txt"));
It's that easy.
"Don't reinvent the wheel."
The best approach to read a file in Java is to open in, read line by line and process it and close the strea
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console - do what you want to do
System.out.println (strLine);
}
//Close the input stream
fstream.close();
To learn more about how to read file in Java, check out the article.
Your question is not very clear, so I'll only answer for the "read" part :
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
lines.add(line);
line = br.readLine();
}
Common used:
String line = null;
File file = new File( "readme.txt" );
FileReader fr = null;
try
{
fr = new FileReader( file );
}
catch (FileNotFoundException e)
{
System.out.println( "File doesn't exists" );
e.printStackTrace();
}
BufferedReader br = new BufferedReader( fr );
try
{
while( (line = br.readLine()) != null )
{
System.out.println( line );
}
#user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[500];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
This is a nice way to work with Streams and Collectors.
List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
myList = reader.lines() // This will return a Stream<String>
.collect(Collectors.toList());
}catch(Exception e){
e.printStackTrace();
}
When working with Streams you have also multiple methods to filter, manipulate or reduce your input.
For Java 11 you could use the next short approach:
Path path = Path.of("file.txt");
try (var reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Or:
var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Or:
Files.lines(Path.of("file.txt")).forEach(System.out::println);

Categories

Resources