Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
thanks to everyone in advance.
I have lines of strings input through a text file and would like to modify the output to remove the last two letters of each string. This is what the text file currently reads:
hello how are you
cool
i am amazing
and this is the code I'm using (from Java-tips.org)
package MyProject
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a text file line by line and print to the console. It uses
* FileOutputStream to read the file.
*
*/
public class FileInput {
public static void main(String[] args) {
File file = new File("MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
// Here BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
// this statement reads the line from the file and print it to
// the console.
System.out.println(dis.readLine());
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The code works perfectly, but I'd like to modify the output to remove the last two letters of each string (string = one per line) Thanks everyone!
Here's my recommendation. Don't use streams for something so trivial and non-load intensive. Stick to the basics, use a Scanner and read your file line-by-line.
Here's the method to success!
Learn how to use a Scanner to read Strings from a text file line-by-line.
Make sure you split the Strings apart with the str.split() method accordingly.
Store each line's String value into a array/list/table.
Modify your stored Strings to remove the last two letters. Look into the str.subString(s,f) method.
Learn how to use a PrintWriter to output your modified Strings to a file.
Good luck!
Comment Reply
Read in a line as a String from texfile.
File file = new File("fileName.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine(); //<------This is a String representation of a line
System.out.println(line); //prints line
//Do your splitting here of lines containing more than 1 word
//Store your Strings here accordingly
//----> Go on to nextLine
}
Related
im tasked with written two java programs. One program creates a file called 'userinput.txt', then writes everything the user inputs into the file. Once done a new file is created called 'Checksum.txt' and this file will write down the checksum for the 'userinput.txt' file after reading whats inside of it.
The 2nd program just reads the same 'userinput.txt' file and then generates a checksum and prints it onto the console (i also have to get the program to read the other checksum.txt file and display it int the console to compare the two but i havent gotten around to that yet).
Iv written the program for these two but my problem is they are both different checksum even though they are reading the same file. Im using Adler32 but CRC32 also gives me two different checksums (the one on console is always different to the one stored in checksum.txt) and im not sure whats causing it frankly :/
Here is the code that takes userinput and generates the checksum file:
package attemp2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
public class main {
public static void main(String[] args) throws IOException {
System.out.println("All inputs will be recorded into a sigle file. Enter 'x' when done. A checksum File will aslo be created at the end");
FileWriter fw = new FileWriter("d:/input.txt", false); // clears previous entry in file.
while (true) {
Scanner input = new Scanner(System.in); //get user input
String ch = input.nextLine(); //stores user input
System.out.println(ch); //prints out what user just inputed
if (ch.equals("x")) { //stops running if 'x' is entered
break;
}
BufferedWriter writer = new BufferedWriter(new FileWriter("d:/input.txt", true));
writer.write(ch);
writer.newLine(); // Add new line
writer.close();
}
try {
FileReader reader = new FileReader("d:/input.txt");
BufferedReader br = new BufferedReader(reader);
// read line by line String line;
String read = "";
String line;
while ((line = br.readLine()) != null) {
read = read + line;
//prints out text in file currently
System.out.println(line);
}
//checksum.txt generation
byte buffer[] = read.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
CheckedInputStream cis = new CheckedInputStream(bais, new Adler32());
byte readBuffer[] = new byte[buffer.length];
cis.read(readBuffer);
FileOutputStream out = new FileOutputStream("d://checksum.txt");
BufferedWriter wrt = new BufferedWriter(new FileWriter("d:/checksum.txt", false));
wrt.write(Long.toString(cis.getChecksum().getValue()));
wrt.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
The code that reads the file and generates a checksum in console:
package check;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.zip.Adler32;
public class CheckSum {
private Adler32 checksum;
private String filepath;
InputStream inputStream;
public CheckSum(String filepath) throws FileNotFoundException{
this.filepath = filepath;
checksum = new Adler32();
inputStream = new FileInputStream(filepath);
}
public long generateChecksum() throws IOException{
int c;
while((c = inputStream.read())!=-1){
checksum.update(c);
}
return checksum.getValue();
}
public void read() throws IOException{
File file = new File(filepath);
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
}
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
String filepath = "d:/input.txt";
CheckSum checksum = new CheckSum(filepath);
checksum.read();
System.out.println("For the file: "+filepath);
System.out.println("The checksum generated is: "+checksum.generateChecksum());
}
}
Please learn how to use a debugger, see What is a debugger and how can it help me diagnose problems?.
That being said, you have some problems with your code. First you are calculating the checksum on an empty array. When you write:
byte readBuffer[] = new byte[buffer.length];
cis.read(readBuffer);
you are reading an empty array of the size of the buffer array. You don't need to create a new array. In fact, you should read the buffer array you already have, since there is your content. In this case you just write:
cis.read(buffer);
The next problem is that you are using readers and writers, which are used for text/string files, but checksum/hash algorithm usually works on byte level. This can result in several errors like encoding (ASCII, UTF-8, etc. stuff) and line-termination issues (\n vs. \r\n vs. \r).
However, in this case you are working with readLine(). This method does not return the line-termination at the end, see the documentation of readLine():
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So, what you are reading from the file is not the same what is actually in the file. But your CheckSum class reads every byte in the saved file (as it should). Assume you enter only the string "abc". Your first calculation will be run on the 3 bytes long array with the values:
[97,98,99]
The line-termination is ignored by the readLine() method, but it is still present in the file. When you check the checksum with the second program, the InputStream you are using will see the following bytes:
[97,98,99,10]
(The bytes at the end depends on the OS you are using)
As you see you run the checksum on different byte arrays, resulting in different checksum values. So, make sure you are running the checksum checks on the same byte array content (or InputStream content) to get the same checksum in both applications.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My text file is in the following format having different type of strings such as below:
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
I would like to remove everything except simple words such as the ones below.
smoldering
temperature
That is if a word is even followed by a comma (e.g. smoldering,), I would remove it.
I tried to remove the digits for a start with MyString.replaceAll("^\\d", " ") but even that is not working.
If you load the entire file into memory, with line breaks, you can use a regex like this:
text = text.replaceAll("(?m)^.*[^a-zA-Z\r\n].*(?:\R|$)", "")
Output
candle
smoldering
temperature
For demo see regex101.
It would however be better to do the filtering while you load the text file:
Pattern simpleWord = Pattern.compile("\\p{L}+"); // one or more Unicode letters
try (BufferedReader in = Files.newBufferedReader(Paths.get("path/to/file.txt"))) {
for (String line; (line = in.readLine()) != null; ) {
if (simpleWord.matcher(line).matches()) {
// found simple word
}
}
}
If you want the simple words in a list, you can simplify that with Java 8 stream:
List<String> simpleWords;
try (Stream<String> lines = Files.lines(Paths.get("path/to/file.txt"))) {
simpleWords = lines.filter(Pattern.compile("^\\p{L}+$").asPredicate())
.collect(Collectors.toList());
}
This solution will iterate over the input.txt lines and paste them into output.txt if they match certain regex. After that it will remove output.txt and rename it with input.txt original file.
Class:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Pattern;
public class ReplaceWithRegex {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (Pattern.matches("^[a-zA-Z]+$", line)) {
writer.write(line);
writer.newLine();
}
}
}
if (inputFile.delete()) {
// Rename the output file to the input file
if (!outputFile.renameTo(inputFile)) {
throw new IOException("Could not rename output to input");
}
} else {
throw new IOException("Could not delete original input file ");
}
}
}
Input.txt
candle
(air-paraffin)
1,000
°c
(1,800
°f)
smoldering
cigarette:
temperature
13%,
wildlife.[14]
johnston,
f.
h.;
keeley,
j.
bibcode:2009sci...324..481b
(http://adsabs.harvard.edu/abs/2009sci...3
Input.txt after execution:
candle
smoldering
temperature
Assuming lines are delimiters:
myString.replaceAll("^[^a-z&&[^A-Z]]*$", "");
This question already has an answer here:
Java PrintWriter not working
(1 answer)
Closed 6 years ago.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileGenerator {
/**
* #param args
*/
public static void main(String[] args) {
File outputFile;
BufferedReader reader;
FileWriter fileWriter;
try {
outputFile = new File("test.txt");
outputFile.createNewFile();
fileWriter = new FileWriter(outputFile, false);
reader = new BufferedReader(new FileReader("template.txt"));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = reader.readLine();
}
String everything = sb.toString();
fileWriter.write(everything);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
}
The fileWriter creates test.txt but the string inside of test.txt is empty. i want it doesnt happen empty. by the way you may say "String everything" can be empty. But it isnt. When i try without reader txt i mean "String everything = "some text", it happens same. it happens empty
The file is empty because the contents of everything are smaller than the operating systems and / or Java's I/O buffers, and the program ends without properly closing the file.
When you write something to a file, and you need to ensure that it is written without closing the file already, call flush().
Whenever you open an I/O resource, close it using close() after use. close() implies flushing the buffers.
Java 7 provides try-with-resources for that, like this:
try (FileWriter writer = new FileWriter("foo.txt")) {
writer.write("Hello, world!\n");
writer.flush();
// do more stuff with writer
} // <- closes writer implicitly as part of the try-with-resources feature
As suggested in the comments, you need to do fileWriter.close() in order to close the output stream. If it is a buffered writer, then closing it not necessary as explained here.
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ive been asked my current program to be saved into a file so it can be continued later even if the program end. However I am new to java, so I Would really appreciate if someone can help me on this :) This is the code i manage to get done, however it just creates an empty file,how am I suppose to go about this problem?
Below is not the whole program coding, i've just copied the codes that is relevant.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileWriter;
public static void main (String[] param) throws FileNotFoundException
{
try
{
fileinputoutput ();
}
catch (FileNotFoundException e)
{
System.exit(0);
}
} // END main
public static void fileinputoutput() throws FileNotFoundException
{
File input = new File("input.txt");
File output = new File("loveletter.txt");
PrintWriter outputFile = new PrintWriter(output);
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputfile = new File(filename);
Scanner newfile = new Scanner(inputfile);
newfile.close();
while(newfile.hasNext())
{
String write = newfile.nextLine();
System.out.println(write);
}
outputFile.close();
}
The answer is pretty obvious. The reason why you only get a blank file is that you never write anything through outputFile and close newfile before you can do anything with it. You should try something like this:
public static void fileinputoutput() throws FileNotFoundException {
File input = new File("input.txt"); // What do you use this variable for? It's never used in the code fragment you posted
File output = new File("loveletter.txt");
PrintWriter outputFile = new FileWriter(output); // I'd personally use FileWriter here
Scanner check = new Scanner(System.in);
String filename = check.nextLine();
File inputFile = new File(filename);
Scanner newfile = new Scanner(inputFile);
while(newfile.hasNext()) {
String write = newfile.nextLine();
outputFile.println(write); // You used to only output something to the console here
}
outputFile.close();
newfile.close();
check.close();
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have 3 text files that all contain strings from objects.
I have a GUI with a list that is populated with the contents of one text file. Im currently looking to implement something that would take the line number from the first file and pull out the strings from the same line number in other files. Can anyone recommend anything?
You can use:
String[] lines = secondFileText.split("\n");
P.s.- If that doesn't work try replacing \n with \r\n.
You can split a string into lines:
String[] lines = s.split("\r?\n");
Then you can access the line at any index:
System.out.println(lines[0]); // The array starts at 0
Note: On Windows, the norm for ending lines is to use a carriage-return followed by a line-feed (CRLF). On Linux, the norm is just LF. The regular expression "\r?\n" caters for both cases - it matches zero or one ("?") carriage-returns ("\r") followed by a line-feed ("\n").
BufferedReader will deal well with huge files that won't fit in memory, it's pretty fast and deal with both \r and \n
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadByLine {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File f = new File("xyz.txt");
int lineNumber = 666;
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
int count = -1;
try {
while((line = br.readLine())!=null){
count++;
if (count == lineNumber){
//get the line, do what you want
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
} catch (IOException e) {
br = null;
}
}
//do what you want with the line
}
}