I would like know how I can remove a blank line while reading/writing a file?
for(int i=1;i<=count;i++) {
FileInputStream fistream1;
try {
name1="file1"+Integer.toString(i)+".txt";
fistream1 = new FileInputStream(name1); // first source file
fistream2 = new FileInputStream("Result.txt"); //second source file
sistream = new SequenceInputStream(fistream2, fistream1);
fostream= new PrintWriter(new BufferedWriter(new FileWriter( result+".txt", true)));
while( ( temp = sistream.read() ) != -1) {
fostream.write(temp); // to write to file
}
fostream.println("");
fostream.close();
sistream.close();
fistream1.close();
fistream2.close();
}
I found this code but I couldn't implement it because of following line:
String line;
while((line = br.readLine())!= null) { ... }
They have used line as a String, but in my case I have temp as int:
int temp;
while((temp = sistream.read())!=-1) { ... }
Is there a way to solve this problem?
The answer of #Abdelhak is not acceptable.
You can try something like this:
while( ( temp = sistream.read() ) != -1) {
if (!temp.trim().equals(""))
{
fostream.write(temp); // to write to file
}
...
The solution was so simple.
I should read lines instead of reading bytes to determine if a line is empty and used a BufferedReader on conjunction with SequenceInputStream.
Related
I have a bit of code to find a string in a text file, print the line the string is on and then print the 5 lines below it. However, I need to modify it so that instead of printing, it deletes/removes the line after the string is found. How would I go about doing this?
File file = new File("./output.txt");
Scanner in = null;
try {
in = new Scanner(file);
while (in.hasNext()) {
String line = in.nextLine();
if (line.contains("(1)")) {
for (int a = 0; in.hasNextLine() && a < 6; a++) {
System.out.println(line);
line = in.nextLine();
}
}
}
} catch (Exception e) {
}
Find a small snippet you can start with.
Assuming your question.txt has the following input.
line 1
line 2
line 3 (1)
line 4
line 5
line 6
line 7
line 8
line 9
line 10
This snippet will print all lines and skip the line line 3 (1) as well the five lines after.
List<String> lines = Files.readAllLines(Paths.get("question.txt"), Charset.defaultCharset());
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).contains("(1)")) {
i = i + 6;
}
System.out.println(lines.get(i));
}
output
line 1
line 2
line 9
line 10
To store the lines into the file is left for you.
My Suggestion is you first declare and initialise a StringBuilder say output before your above code like:
StringBuilder output = new StringBuilder();
Now after the close of the if statement before the closing of the while loop append the line to the output and add a "\n" at the end like this:
output.append(line+"\n");
Now finally after your code that you have posted create a FileWriter say writer and then use the writer to write the output as shown below:
try(FileWriter writer = new FileWriter(file, false)){
writer.write(output);
}catch IOException(e){
e.printStackTrace();
}
Also don't forget to remove or comment out the following line if you do not want them printed in the output.
System.out.println(line);
SubOtimal has a good, concise answer that will work for most cases. The following is more complex but avoids loading the whole file into memory. That probably isn't an issue for you but just in case...
public void deleteAfter(File file, String searchString, int lineCountToDelete) {
// Create a temporary file to write to
File temp = new File(file.getAbsolutePath() + ".tmp");
try (BufferedReader reader = new BufferedReader(new FileReader(file));
PrintWriter writer = new PrintWriter(new FileWriter(temp)) ) {
// Read up to the line we are searching for
// and write each to the temp file
String line;
while((line = reader.readLine()) != null && !line.equals(searchString)){
writer.println(line);
}
// Skip over the number of lines we want to "delete"
// as well as watching out for hitting the end of the file
for(int i=0;i < lineCountToDelete && line != null; i++){
line = reader.readLine();
}
// Write the remaining lines to the temp file.
while((line = reader.readLine()) != null){
writer.println(line);
}
} catch (IOException e) {
throw new IllegalStateException("Unable to delete the lines",e);
}
// Delete the original file
if(!file.delete()){
throw new IllegalStateException("Unable to delete file: " + file.getAbsolutePath());
}
// Rename the temp file to the original name
if(!temp.renameTo(file)){
throw new IllegalStateException("Unable to rename " +
temp.getAbsolutePath() + " to " + file.getAbsolutePath());
}
}
I tested this with multiple conditions, including a line that doesn't exist, a line at the end and a line with fewer lines left than the number to skip. All worked and gave the appropriate results.
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.
What I am doing is to read one file line by line, format every line, then write to a new file. But the problem is that the file is huge, nearly 178 MB. But always getting error message: IO console updater error, java heap space. Here is my code:
public class fileFormat {
public static void main(String[] args) throws IOException{
String strLine;
FileInputStream fstream = new FileInputStream("train_final.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
BufferedWriter writer = new BufferedWriter(new FileWriter("newOUTPUT.txt"));
while((strLine = reader.readLine()) != null){
List<String> numberBox = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(strLine);
while(st.hasMoreTokens()){
numberBox.add(st.nextToken());
}
for (int i=1; i< numberBox.size(); i++){
String head = numberBox.get(0);
String tail = numberBox.get(i);
String line = head + " "+tail ;
System.out.println(line);
writer.write(line);
writer.newLine();
}
numberBox.clear();
}
reader.close();
writer.close();
}
}
How can I avoid this error message? Moreover, I have set the VM preference: -xms1024m
Remove the line
System.out.println(line);
This is a workaround the fialing console updater, which otherwise runs out of memory.
The program looks okay. I suspect the problem is that you run this inside of Eclipse, and System.out is collected by Eclipse in memory (to be displayed in that Console window).
System.out.println(line);
Try to run it outside of Eclipse, change Eclipse settings to pipe System.out somewhere, or remove the line.
This part of the code:
for (int i=1; i< numberBox.size(); i++){
String head = numberBox.get(0);
String tail = numberBox.get(i);
String line = head + " "+tail ;
System.out.println(line);
writer.write(line);
writer.newLine();
}
Can be translated to:
String head = numberBox.get(0);
for (int i=1; i< numberBox.size(); i++){
String tail = numberBox.get(i);
System.out.print(head);
System.out.print(" ");
System.out.println(tail);
writer.write(head);
writer.write(" ");
writer.write(tail);
writer.newLine();
}
This may add a little code duplication but it avoids creating a lot of objects.
Also there if you merge this for loop with the loop contructing the numberBox, you won't need numberBox structure at all.
If you read whole file the heap memory will occupy so better option in to read the file in chuck. See my below code. It will start reading from the offset given in argument and will return the end offset . You need to pass number of lines to be read.
Please remember: You can use any collection to store these read lines and clear the collection before calling this method to read next chunk.
FileInputStream fis = new FileInputStream(file);
InputStreamReader streamReader = new InputStreamReader(fis, "UTF-8");
LineNumberReader reader = new LineNumberReader(streamReader);
//call this below method recursively until the file does not reaches to the end
public int getParsedLines(LineNumberReader reader, int iLineNumber_Start, int iNumberOfLinesToBeRead) {
int iLineNumber_End = 0;
int iReadUptoLines = iLineNumber_Start + iNumberOfLinesToBeRead;
try {
reader.mark(iLineNumber_Start);
reader.setLineNumber(iLineNumber_Start);
do {
String str = reader.readLine();
if (str == null) {
break;
}
// your code
iLineNumber_End = reader.getLineNumber();
} while (iLineNumber_End != iReadUptoLines);
} catch (Exception ex) {
// exception handling
}
return iLineNumber_End;
}
I need to copy a line from a file to another depending on condition
this is my code
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String args[]) throws IOException {
File source = \\
File fileToCopyFrom \\
File target :\\
if (!target.exists()) {
target.createNewFile();
}
PrintStream fstream =new PrintStream(target);
BufferedReader brSource = new BufferedReader(new FileReader(source));
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
String lineSource;
String lineToCopy;
while((lineSource = brSource.readLine()) != null) {
while ((lineToCopy=brFileToCopyFrom.readLine())!=null) {
if (lineToCopy.contains(lineSource.substring(lineSource.indexOf("_")+1, lineSource.indexOf(".")-1)))
fstream.println(lineToCopy);
}
}
}}
but it copy only the first line
where is the error?
Only the first is copied because in the second iteration of the first while the brFileToCopyFrom is reached the end of file.
You need to open the BufferedReader brFileToCopy inside the first while (example 1) or use a mark/reset feature (example 2).
Example 1:
while ((lineSource = brSource.readLine()) != null) {
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
...
}
}
}
Example 2:
brFileToCopyFrom.mark(1024); // number of characters to be read while preserving the mark
while ((lineSource = brSource.readLine()) != null) {
brFileToCopyFrom.reset();
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
...
}
}
}
I suggest to use commons-io.jar. In this FileUtils class lot of methods to do File operation like copy, move and remove.
EDIT
try with below if conndition which contains break.
while ((lineSource = brSource.readLine()) != null) {
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
if (lineToCopy.contains(lineSource.substring(
lineSource.indexOf("_") + 1,
lineSource.indexOf(".") - 1))) {
fstream.println(lineToCopy);
break;
}
}
}
you create your stream, you read all enntries from your stream, for first line, but when you want to do this for second line brFileToCopyFrom is empty (you already took everything from it when you were checking your first line.
so what you could do is move creating your brFileToCopyFrom to the loop,
while((lineSource = brSource.readLine()) != null) {
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
...
that should works
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);