What are the file output limits with my code? - java

I just made a very simple parser that gets input from a file and outputs to a file.
It does a line-by-line parsing of the file you give it and iterates the same function for all lines of the file and then it redirects the whole string to another file.
I give the parseLine function a JsonObjectBuilder so that it can keep on adding json-like structures to the output string (it's a normal text to json parser btw).
parseFile function
private String parseFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
String line;
try{
while((line = reader.readLine()) != null){
parseLine(line, jsonBuilder);
}
} finally {
reader.close();
}
return jsonBuilder.build().toString();
}
Parser class
public Parser(String file) throws IOException {
PrintWriter out = new PrintWriter(System.getProperty("user.dir") + "/parser/src/main/resources/logFormatted.log");
System.out.println("Initiated Parser class!");
out.println(parseFile(file));
}
parseLine function
private JsonObjectBuilder parseLine(String line, JsonObjectBuilder jsonBuilder){
String timestamp = null;
String eventCode = null;
String payload = null;
String finalString = null;
try {
timestamp = line.substring(0, 23);
eventCode = line.substring(24, 28);
payload = line.substring(29, line.length());
jsonBuilder.add(timestamp, Json.createObjectBuilder()
.add("eventCode", eventCode)
.add("payload", payload)
);
} catch (Exception ex) {
System.out.println("ERROR: " + ex);
}
return jsonBuilder;
}
Main
public static void main( String[] args ) throws IOException{
Parser parser = new Parser(System.getProperty("user.dir") + "/parser/src/main/resources/newFormatLog.log");
}
The problem with this code is that when it's executed it parses like it's supposed to but doesn't parse the whole file. Right now I'm giving it a ~4550 lines file but it does output a ~4400 line one.
I really don't know why and I'm starting to think the string is too big to handle or something. Maybe I need to output the lines immediatly to the file rather than doing a final big wite. All help is very appreciated!

Found out the problem. It was really dumb.
public Parser(String file) throws IOException {
PrintWriter out = new PrintWriter(System.getProperty("user.dir") + "...");
System.out.println("Initiated Parser class!");
out.println(parseFile(file));
}
In this constructor I was not closing the PrintWriter. Just added out.close(); and everything worked as expected.
public Parser(String file) throws IOException {
try (PrintWriter out = new PrintWriter(System.getProperty("user.dir") + "...")) {
System.out.println("Initiated Parser class!");
out.println(parseFile(file));
}
}
You can refer to this other question as reference.
EDIT: Added try(PrintWriter out = ...) as suggested in the comments

Related

How to delete a line of string in a text file - Java [duplicate]

I'm looking for a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following:
myFile.txt:
aaa
bbb
ccc
ddd
Need to have a function like this: public void removeLine(String lineContent), and if I pass
removeLine("bbb"), I get file like this:
myFile.txt:
aaa
ccc
ddd
This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
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"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
This I have found on the internet.
You want to do something like the following:
Open the old file for reading
Open a new (temporary) file for writing
Iterate over the lines in the old file (probably using a BufferedReader)
For each line, check if it matches what you are supposed to remove
If it matches, do nothing
If it doesn't match, write it to the temporary file
When done, close both files
Delete the old file
Rename the temporary file to the name of the original file
(I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)
So, whenever I hear someone mention that they want to filter out text, I immediately think to go to Streams (mainly because there is a method called filter which filters exactly as you need it to). Another answer mentions using Streams with the Apache commons-io library, but I thought it would be worthwhile to show how this can be done in standard Java 8. Here is the simplest form:
public void removeLine(String lineContent) throws IOException
{
File file = new File("myFile.txt");
List<String> out = Files.lines(file.toPath())
.filter(line -> !line.contains(lineContent))
.collect(Collectors.toList());
Files.write(file.toPath(), out, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
}
I think there isn't too much to explain there, basically Files.lines gets a Stream<String> of the lines of the file, filter takes out the lines we don't want, then collect puts all of the lines of the new file into a List. We then write the list over top of the existing file with Files.write, using the additional option TRUNCATE so the old contents of the file are replaced.
Of course, this approach has the downside of loading every line into memory as they all get stored into a List before being written back out. If we wanted to simply modify without storing, we would need to use some form of OutputStream to write each new line to a file as it passes through the stream, like this:
public void removeLine(String lineContent) throws IOException
{
File file = new File("myFile.txt");
File temp = new File("_temp_");
PrintWriter out = new PrintWriter(new FileWriter(temp));
Files.lines(file.toPath())
.filter(line -> !line.contains(lineContent))
.forEach(out::println);
out.flush();
out.close();
temp.renameTo(file);
}
Not much has been changed in this example. Basically, instead of using collect to gather the file contents into memory, we use forEach so that each line that makes it through the filter gets sent to the PrintWriter to be written out to the file immediately and not stored. We have to save it to a temporary file, because we can't overwrite the existing file at the same time as we are still reading from it, so then at the end, we rename the temp file to replace the existing file.
Using apache commons-io and Java 8 you can use
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);
public static void deleteLine() throws IOException {
RandomAccessFile file = new RandomAccessFile("me.txt", "rw");
String delete;
String task="";
byte []tasking;
while ((delete = file.readLine()) != null) {
if (delete.startsWith("BAD")) {
continue;
}
task+=delete+"\n";
}
System.out.println(task);
BufferedWriter writer = new BufferedWriter(new FileWriter("me.txt"));
writer.write(task);
file.close();
writer.close();
}
Here you go. This solution uses a DataInputStream to scan for the position of the string you want replaced and uses a FileChannel to replace the text at that exact position. It only replaces the first occurrence of the string that it finds. This solution doesn't store a copy of the entire file somewhere, (either the RAM or a temp file), it just edits the portion of the file that it finds.
public static long scanForString(String text, File file) throws IOException {
if (text.isEmpty())
return file.exists() ? 0 : -1;
// First of all, get a byte array off of this string:
byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
// Next, search the file for the byte array.
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
List<Integer> matches = new LinkedList<>();
for (long pos = 0; pos < file.length(); pos++) {
byte bite = dis.readByte();
for (int i = 0; i < matches.size(); i++) {
Integer m = matches.get(i);
if (bytes[m] != bite)
matches.remove(i--);
else if (++m == bytes.length)
return pos - m + 1;
else
matches.set(i, m);
}
if (bytes[0] == bite)
matches.add(1);
}
}
return -1;
}
public static void replaceText(String text, String replacement, File file) throws IOException {
// Open a FileChannel with writing ability. You don't really need the read
// ability for this specific case, but there it is in case you need it for
// something else.
try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) {
long scanForString = scanForString(text, file);
if (scanForString == -1) {
System.out.println("String not found.");
return;
}
channel.position(scanForString);
channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */)));
}
}
Example
Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Method Call:
replaceText("QRS", "000", new File("path/to/file");
Resulting File: ABCDEFGHIJKLMNOP000TUVWXYZ
Here is the complete Class. In the below file "somelocation" refers to the actual path of the file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileProcess
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("C://somelocation//Demographics.txt");
File tempFile = new File("C://somelocation//Demographics_report.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
if(null!=currentLine && !currentLine.equalsIgnoreCase("BBB")){
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
This solution reads in an input file line by line, writing each line out to a StringBuilder variable. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. Then it deletes file content and put the StringBuilder variable content.
public void removeLineFromFile(String lineToRemove, File f) throws FileNotFoundException, IOException{
//Reading File Content and storing it to a StringBuilder variable ( skips lineToRemove)
StringBuilder sb = new StringBuilder();
try (Scanner sc = new Scanner(f)) {
String currentLine;
while(sc.hasNext()){
currentLine = sc.nextLine();
if(currentLine.equals(lineToRemove)){
continue; //skips lineToRemove
}
sb.append(currentLine).append("\n");
}
}
//Delete File Content
PrintWriter pw = new PrintWriter(f);
pw.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(f, true));
writer.append(sb.toString());
writer.close();
}
Super simple method using maven/gradle+groovy.
public void deleteConfig(String text) {
File config = new File("/the/path/config.txt")
def lines = config.readLines()
lines.remove(text);
config.write("")
lines.each {line -> {
config.append(line+"\n")
}}
}
public static void deleteLine(String line, String filePath) {
File file = new File(filePath);
File file2 = new File(file.getParent() + "\\temp" + file.getName());
PrintWriter pw = null;
Scanner read = null;
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel src = null;
FileChannel dest = null;
try {
pw = new PrintWriter(file2);
read = new Scanner(file);
while (read.hasNextLine()) {
String currline = read.nextLine();
if (line.equalsIgnoreCase(currline)) {
continue;
} else {
pw.println(currline);
}
}
pw.flush();
fis = new FileInputStream(file2);
src = fis.getChannel();
fos = new FileOutputStream(file);
dest = fos.getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) {
e.printStackTrace();
} finally {
pw.close();
read.close();
try {
fis.close();
fos.close();
src.close();
dest.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file2.delete()) {
System.out.println("File is deleted");
} else {
System.out.println("Error occured! File: " + file2.getName() + " is not deleted!");
}
}
}
package com.ncs.cache;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class FileUtil {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
// Construct the new file that will later be renamed to the original
// filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
// Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("test.txt", "bbbbb");
}
}
src : http://www.javadb.com/remove-a-line-from-a-text-file/
This solution requires the Apache Commons IO library to be added to the build path. It works by reading the entire file and writing each line back but only if the search term is not contained.
public static void removeLineFromFile(File targetFile, String searchTerm)
throws IOException
{
StringBuffer fileContents = new StringBuffer(
FileUtils.readFileToString(targetFile));
String[] fileContentLines = fileContents.toString().split(
System.lineSeparator());
emptyFile(targetFile);
fileContents = new StringBuffer();
for (int fileContentLinesIndex = 0; fileContentLinesIndex < fileContentLines.length; fileContentLinesIndex++)
{
if (fileContentLines[fileContentLinesIndex].contains(searchTerm))
{
continue;
}
fileContents.append(fileContentLines[fileContentLinesIndex] + System.lineSeparator());
}
FileUtils.writeStringToFile(targetFile, fileContents.toString().trim());
}
private static void emptyFile(File targetFile) throws FileNotFoundException,
IOException
{
RandomAccessFile randomAccessFile = new RandomAccessFile(targetFile, "rw");
randomAccessFile.setLength(0);
randomAccessFile.close();
}
I refactored the solution that Narek had to create (according to me) a slightly more efficient and easy to understand code. I used embedded Automatic Resource Management, a recent feature in Java and used a Scanner class which according to me is more easier to understand and use.
Here is the code with edited Comments:
public class RemoveLineInFile {
private static File file;
public static void main(String[] args) {
//create a new File
file = new File("hello.txt");
//takes in String that you want to get rid off
removeLineFromFile("Hello");
}
public static void removeLineFromFile(String lineToRemove) {
//if file does not exist, a file is created
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("File "+file.getName()+" not created successfully");
}
}
// Construct the new temporary file that will later be renamed to the original
// filename.
File tempFile = new File(file.getAbsolutePath() + ".tmp");
//Two Embedded Automatic Resource Managers used
// to effectivey handle IO Responses
try(Scanner scanner = new Scanner(file)) {
try (PrintWriter pw = new PrintWriter(new FileWriter(tempFile))) {
//a declaration of a String Line Which Will Be assigned Later
String line;
// Read from the original file and write to the new
// unless content matches data to be removed.
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
// Delete the original file
if (!file.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(file))
System.out.println("Could not rename file");
}
}
catch (IOException e)
{
System.out.println("IO Exception Occurred");
}
}
}
Try this:
public static void main(String[] args) throws IOException {
File file = new File("file.csv");
CSVReader csvFileReader = new CSVReader(new FileReader(file));
List<String[]> list = csvFileReader.readAll();
for (int i = 0; i < list.size(); i++) {
String[] filter = list.get(i);
if (filter[0].equalsIgnoreCase("bbb")) {
list.remove(i);
}
}
csvFileReader.close();
CSVWriter csvOutput = new CSVWriter(new FileWriter(file));
csvOutput.writeAll(list);
csvOutput.flush();
csvOutput.close();
}
Old question, but an easy way is to:
Iterate through file, adding each line to an new array list
iterate through the array, find matching String, then call the remove method.
iterate through array again, printing each line to the file, boolean for append should be false, which basically replaces the file
This solution uses a RandomAccessFile to only cache the portion of the file subsequent to the string to remove. It scans until it finds the String you want to remove. Then it copies all of the data after the found string, then writes it over the found string, and everything after. Last, it truncates the file size to remove the excess data.
public static long scanForString(String text, File file) throws IOException {
if (text.isEmpty())
return file.exists() ? 0 : -1;
// First of all, get a byte array off of this string:
byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
// Next, search the file for the byte array.
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
List<Integer> matches = new LinkedList<>();
for (long pos = 0; pos < file.length(); pos++) {
byte bite = dis.readByte();
for (int i = 0; i < matches.size(); i++) {
Integer m = matches.get(i);
if (bytes[m] != bite)
matches.remove(i--);
else if (++m == bytes.length)
return pos - m + 1;
else
matches.set(i, m);
}
if (bytes[0] == bite)
matches.add(1);
}
}
return -1;
}
public static void remove(String text, File file) throws IOException {
try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) {
long scanForString = scanForString(text, file);
if (scanForString == -1) {
System.out.println("String not found.");
return;
}
long remainderStartPos = scanForString + text.getBytes().length;
rafile.seek(remainderStartPos);
int remainderSize = (int) (rafile.length() - rafile.getFilePointer());
byte[] bytes = new byte[remainderSize];
rafile.read(bytes);
rafile.seek(scanForString);
rafile.write(bytes);
rafile.setLength(rafile.length() - (text.length()));
}
}
Usage:
File Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Method Call: remove("ABC", new File("Drive:/Path/File.extension"));
Resulting Contents: DEFGHIJKLMNOPQRSTUVWXYZ
This solution could easily be modified to remove with a certain, specifiable cacheSize, if memory is a concern. This would just involve iterating over the rest of the file to continually replace portions of size, cacheSize. Regardless, this solution is generally much better than caching an entire file in memory, or copying it to a temporary directory, etc.

How to read from a file and then analyze this data?

I am a begginer(recently began learning) at programming in Java and I need help.
I have to read from a file, which contains numbers. I would like to make a method for reading from a file. Then I need to analyze this data and write it in another file.
What I strugle with is if I make a method just to read from a file or do I also have to save this read data into a variable. Where should this variable be declared inside a method (if is inside, how do I use it outside), if is outside how do I use it inside a method and also outside. Can anyone help me clarify this? What am I doing wrong?
My code of what I wrote until now. File from which I had to read has houndreds of numbers.
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
File file = new File(nameFile);
String contentFile ="";
}
//Method for reading a .txt file
private static String readFromFile(String nameFile, String contentFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
while((line = read.readLine()) != null) {
line = contentFIle;
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
}
Theoretically speaking: mathematical functions get input variables, they preform some transformation on the variables and output the result of the transformation.
For example: f(x) = x - 1, g(x) = x * 2
You can chain functions in a way that one functions output will be the other function input: g(f(2)). In this case, the number 2 is used as an input for function f(x) and the output of f(x) is the input of g(x).
Functions and methods in programming can work in a similar way, but It may be more readable to save function output into meaningful variable names, and then to apply these variables to the next function.
Instead of doing: outputText(processText(readText(someFilename)))
You can write (pseudocode):
someFilename = 'foo'
text = readText(someFilename)
processed = processText(text)
outputText(processed)
In java and in your context this would look like the following:
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFileByName(nameFile);
String altered = processText(contentFile);
saveToFile(altered, "processed.txt");
}
private static String readFromFileByName(String nameFile) {
String fullRead = "";
try {
File file = new File(nameFile);
BufferedReader read = new BufferedReader(new FileReader(file));
String line; // define line variable
while((line = read.readLine()) != null) {
fullRead += line; // pay attention for the altered code
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
} finally {
return fullRead;
}
}
private static List<Integer> stringToIntList(String string) {
return Arrays
.stream(text.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private static String processText(String text) {
String processed = text.replace('H', 'h'); // Some heavy processing :)
return processed;
}
private static void saveToFile(String text, String fileName) {
// save <text> to file with filename <filename>
}
}
1) Line is the variable that you have read to. So you shouldn't change its value.
line = contentFIle;
if you need only first line this method should look like:
private static String readFromFile(String nameFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
line = read.readLine();
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
if you need a list of this:
List<String> lines = Collections.emptyList();
try {
Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
} catch (IOException e) {
// do something
e.printStackTrace();
}
return lines;
2) Also you don't call readFromFile function. So you need to change the main method:
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFile(nameFile);
}
3)For your particular case, there's no sense to call readFromFile with String contentFile because you don't use this variable.

get Data from text file in java [duplicate]

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Iterative function issue

Im having some issues with a function that I have written. The function basically takes a file and a string into the method as parameters and searches the file for that string and replaces it with "".
public void removeReminder(File a, String search) throws IOException {
File tempFile = File.createTempFile("file", ".txt", a.getParentFile());
BufferedReader br = new BufferedReader(new FileReader(a));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
for (String line; (line = br.readLine()) != null;) {
line = line.replace(search, "");
pw.println(line);
}
br.close();
pw.close();
a.delete();
tempFile.renameTo(a);
}
I then have 3 text files that I need to run this method for. Below is the code where i run the function.
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// TODO
try {
String names = reminderNameField.getText();
String date = reminderDate.getText();
String details = reminderDetailsField.getText();
File fileName = new File("reminderNames.txt");
File fileDate = new File("reminderDate.txt");
File fileDetails = new File("reminderDetails.txt");
removeReminder(fileName, names);
removeReminder(fileDate, date);
removeReminder(fileDetails, details);
} catch (IOException e){
e.printStackTrace();
}
I dont know why this isnt working. It works for the first iteration (e.g removeReminder(fileName, names);) But it doesnt work for the other ones, it seems to just ignore them :s can anyone tell me why this is?
I always flush printwriter. Try flushing PrintWriter before calling close().
pw.flush();

File write/read function like in PHP

So I'm learning new things day by day in Java, and I hope one day I should have same knowledge in Java as in PHP.
I'm trying to make a class that is similar to fopen, fwrite, fclose in PHP like:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
I also need the method of writing
o - for delete and write/overwrite
a - for append at end
and a read function that returns the the content line by line, so I can put it into an array , like file_get_contents(file);
This is what I have so far ...
import java.io.*;
import java.util.Scanner;
/**
Read and write a file using an explicit encoding.
Removing the encoding from this code will simply cause the
system's default encoding to be used instead.
**/
public final class readwrite_txt
{
/** Requires two arguments - the file name, and the encoding to use. **/
public static void main(String[] args) throws IOException
{
String fileName = "text.txt";
String encoding = "UTF-8";
readwrite_txt test = new readwrite_txt(fileName,encoding);
test.write("argument.txt","some text","UTF-8","o");
}
/** Constructor. **/
readwrite_txt(String fileName, String encoding)
{
String fEncoding = "text.txt";
String fFileName = "UTF-8";
}
/** Write fixed content to the given file. **/
public void write(String fileName,String input,String encoding,String writeMethod) throws IOException
{
// Method overwrite
if(writeMethod == "o")
{
log("Writing to file named " + fileName + ". Encoding: " + encoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
try
{
out.write(input);
}
finally
{
out.close();
}
}
}
/** Read the contents of the given file. **/
public void read(String fileName,String output,String encoding,String outputMethod) throws IOException
{
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);
try
{
while (scanner.hasNextLine())
{
text.append(scanner.nextLine() + NL);
}
}
finally
{
scanner.close();
}
log("Text read in: " + text);
}
// Why write System.out... when you can make a function like log("message"); simple!
private void log(String aMessage)
{
System.out.println(aMessage);
}
}
also, I don't understand why I must have
readwrite_txt test = new readwrite_txt(fileName,encoding);
instead of
readwrite_txt test = new readwrite_txt();
I just want to have an simple function similar to that in PHP.
EDITED
So my function must be
$fp = fopen('data.txt', 'w'); ==> readwrite_txt test = new readwrite_txt(filename,encoding,writeMethod);
fwrite($fp, '23'); ==> test.write("the text");
fclose($fp); ==> ???
to read a file in java you can
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) //Start of reading file
{
//what you want to do with every line is here
}
but for readwrite_txt test = new readwrite_txt(); problem ..
you must have another constructor inside the class that doesn't take any parameters
Have a look at the following file handling tutorials (Google is littered with them):
http://www.javapractices.com/topic/TopicAction.do?Id=42
http://www.coderanch.com/t/403914/java/java/do-read-entire-file-all
Pay attention to the following classes:
FileInputStream
FileOutpuStream
Scanner
There's all sorts of examples out there for you to learn from.
You can use the BufferedReader, here is an example and BufferedWriter, here is an example of write and here is an example for appending. For reading line-by-line you can use the readLine method of BufferedReader. You don't need those parameters in your constructor, because you don't use them, but you don't even need a class to implement these features because there are already standard classes for this purpose.
I hope this helps.

Categories