I have a String like "HelloWorld!9090Hello" in a file, and i want to replace the whole string with a new One, Tried this but didn't helped
Example File abc.txt:
a=HelloWorld!9090Hello
String neww = "abcdef";
File file = new File("abc.txt");
File wr = new File("tmp.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// tried even line.toString();//
String rline= line.replace("HelloWorld!9090Hello", neww);
BufferWrite(rline,wr);
}
br.close();
public static void BufferWrite(String St,File file) throws IOException{
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(St);
bw.write("\r\n");
bw.close();
}
The BufferWrite() writes text to the tmp.txt file..
Result :
a=HelloWorld!9090Hello
I ran your exact code in Eclipse, and it creates the tmp file correctly for me and it has "abcdef" in it.
Did you make sure you actually started with exactly "HelloWorld!9090Hello" in your input file? It looks like you are starting with "a=HelloWorld!9090Hello", not "HelloWorld!9090Hello". The replace function will only work when the Strings are an exact match. If you're starting with "a=HelloWorld!9090Hello", change the replace function to the following:
String rline= line.replace("a=HelloWorld!9090Hello", neww);
Related
I am writing a little app where I go to an api, get some json data and fill that into a csv file.
It works so far, that I get a csv file, with the correct rows, but instead of columns there are still commas in text form in file.
I am using opencsv.
private void writeCsv(InputStream input, String name) throws IOException {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
StringBuilder text = new StringBuilder();
while ((line = reader.readLine()) != null) {
text.append(line);
}
JSONArray docs = new JSONArray(text.toString());
File file=new File(name + ".csv");
String csv = CDL.toString(docs);
CSVWriter writer = new CSVWriter(new FileWriter(file));
BufferedReader sreader = new BufferedReader(new StringReader(csv));
String csvline;
while ((csvline = sreader.readLine()) != null) {
writer.writeNext(csvline);
}
writer.close();
System.out.println("done");
}
You need to add column mapping strategy.
ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
check this blog for better understanding.
http://www.javainterviewpoint.com/csvtobean-and-beantocsv-example-using-opencsv/
I have a text file "test.txt" with the following content
********************
Hi
This is ABC
I learning JAVA and would like to expertize in it.
I joined Stackoverflow today.
********************
My requirement is to make the line #4 - I joined Stackoverflow today. as the first line in test.txt so that the file content is as follows:
********************
I joined Stackoverflow today.
Hi
This is ABC
I learning JAVA and would like to expertize in it.
I joined Stackoverflow today.
********************
Can this be done via code, as I am trying to use various Java Utils, but I am unable to make the line move to the first place.
May not be the best way, but works!
First Delete the line
File inputFile = new File("test.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "I joined Stackoverflow today.";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
boolean successful = tempFile.renameTo(inputFile);
writer.close();
reader.close();
Then Append it at the beginning of your file
RandomAccessFile f = new RandomAccessFile(new File("yourtextfile.txt"), "rw");
f.seek(0); // to the beginning
f.write(lineToRemove.getBytes());
f.close();
the input file being used has duplicates records
DETAILS:
aa
bb
aa
gg
bb
bb
To remove duplicates, I am using the following code
File Readfile= new File(n.getProperty("file"));
BufferedReader reader= new BufferedReader(new FileReader(Readfile));
Set<String> lines = new HashSet<String>(10000);
String line;
while((line=reader.readLine())!=null){
lines.add(line);
}
reader.close();
File file =new File("stripduplicates.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file.getPath()));
//EDIT done
writer.write("DETAILS:");
for(String unique: lines){
//EDIT done
if(!(unique.startsWith("DETAILS:"))
{
writer.write(unique);
writer.newLine();
}
}
writer.close();
}
The output is coming as needed
DETAILS:
aa
gg
bb
I have to read from a text file and format the input. I'm new to java reading from files, and I don't know how to work with just some parts of what I read
Here is the initial file: http://pastebin.com/D0paWtAd
And I have to write in another file the following output:
Average,Joe,44,31,18,12,9,10
I've managed just to take everything from the file and print it to output. I would need help just in taking the output I need and print it to the screen. Any help is appreciated.
This is what I wrote up to now:
public class FileParsing {
public static String
read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Bogdi\\Desktop\\example.txt"));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) sb.append(s + "\n");
in.close();
return sb.toString();
}
If your goal is to do the specified output in another file you don't need to first get the content of your file in a StringBuilder before processing it, you can append the processed datas directly in a StringBuilder then you can write the result in a file. Here is an example that would work for the given file but you may have to modify it if the keys change in the future:
The following method will correctly process the datas from your file
public static String read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) {
String[] split1 = s.split("=");
if (split1[0].equals("name")) {
StringTokenizer tokenizer = new StringTokenizer(split1[1]);
sb.append(tokenizer.nextToken());
sb.append(",");
sb.append(tokenizer.nextToken());
sb.append(",");
} else if (split1[0].equals("index")) {
sb.append(split1[1] + ",");
} else if (split1[0].equals("FBid")) {
sb.append(split1[1]);
} else {
StringTokenizer tokenizer = new StringTokenizer(split1[1]);
String wasted = tokenizer.nextToken();
sb.append(tokenizer.nextToken() + ",");
}
}
in.close();
return sb.toString();
}
The next method will read any string to a file
public static void writeStringToFile(String string, String filePath) throws IOException {
BufferedWriter writer = new BufferedWriter(
new FileWriter(
new File(filePath)
)
);
writer.write(string);
writer.newLine();
writer.flush();
writer.close();
}
And here is a simple tests (File1.txt contains the datas from the file you shared on paste bin and I write them in another file)
public static void main(String[] args) throws Exception {
String datas = read("C:\\Tests\\File1.txt");
System.out.println(datas);
writeStringToFile(datas, "C:\\Tests\\FileOuput.txt" );
}
It will produce the exact output that you are expecting
[EDIT] #idk, apparently you have an exception executing my example, while it is working fine for me. That could only mean there is an error at data level. Here is the data sample that I used (and I believe I exactly copy the datas you shared)
And here is the result:
Good to know you are using "StringBuilder" component instead being concatenating your String values, way to go :).
More than knowledge on the Java.IO API to work with files, you will need some logic to get the results you expect. Here I came with an approach that could help you, not perfect, but can point you on how to face this problem.
//Reference to your file
String myFilePath = "c:/dev/myFile.txt";
File myFile = new File(myFilePath);
//Create a buffered reader, which is a good start
BufferedReader breader = new BufferedReader(new FileReader(myFile));
//Define this variable called line that will evaluate each line of our file
String line = null;
//I will use a StringBuilder to append the information I need
StringBuilder appender = new StringBuilder();
while ((line = breader.readLine()) != null) {
//First, I will obtain the characters after "equals" sign
String afterEquals = line.substring(line.indexOf("=") + 1, line.length());
//Then, if it contains digits...
if (afterEquals.matches(".*\\d+.*")) {
//I will just get the digits from the line
afterEquals = afterEquals.replaceAll("\\D+","");
}
//Finally, append the contents
appender.append(afterEquals);
appender.append(",");//This is the comma you want to include
}
//I will delete the last comma
appender.deleteCharAt(appender.length() - 1);
//Close the reader...
breader.close();
//Then create a process to write the content
BufferedWriter myWriter = new BufferedWriter(new FileWriter(new File("myResultFile.txt")));
//Write the full contents I get from my appender :)
myWriter.write(appender.toString());
//Close the writer
myWriter.close();
}
Hope this can help you. Happy coding!
I want add few strings to a text file in a particular location.
I have used BufferedReader to read the text file. Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter.
Then I deleted the old file and renamed the temp file to old file name.
This works sometimes and does not work sometimes. The delete() function sometimes does not delete the file. I have closed all the BufferedWriter's, but the problem still occurs sometimes.
Code:
public boolean cart(String uname, String item) throws IOException {
File file = new File("C:\\$$$$.tmp");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
File fileop = new File("C:\\value.text");
FileReader fr = new FileReader(fileop.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String val[] = line.split(",");
if (val[0].equals(uname)) {
String linenew = line + item + "&";
bw.append(linenew);
bw.newLine();
bw.flush();
} else {
bw.append(line);
bw.newLine();
bw.flush();
}
}
br.close();
bw.close();
fileop.delete();
file.renameTo(fileop);
return true;
}
I found the answer by myself after spending one full day of searching..
Answer is:
It is enough to close the bufferedReader but also the fileReader..
fr.close(); should be inserted after br.close();
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);