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.
Related
I'm pretty new in the programming world, and i can't find a good explanation on how to to load a txt file to a string variable in java using eclpise.
So far, from what i have been able to understand, i am supposed to use the StdIn class, and i know that the txt file need to be located in my eclipse workspace (outside the source folder) but i don't know what excatly i need to write in the code to get the given file to load into the variable.
I could really use some help with this.
Although I'm not a Java expert, I'm pretty sure this is the information you're looking for It looks like this:
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
Basically all languages provide you with some methods to read from the file system you're in. Hope that does it for you!
Good luck with your project!
to read a file and store it in a String you can do it by using either String or StringBuilder:
you need to define BufferedReader to with constructor of FileReader to pass the name of the file and make it ready to read from file.
use StringBuilder to append every line of result to it.
when the reading finished add the result to String data.
public static void main(String[] args) {
String data = "";
try {
BufferedReader br = new BufferedReader(new FileReader("filename"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
data = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
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.
A method returns a String in comma separated format. For example, the returned String can be like the one given below.
Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China
I will need to get this String and write it into a CSV file. I'll have to insert a header and a footer for this file as well.
For example, when I open the file, the contents for the above data will be
Name,Age,Gender,Country
Tarantino,50,M,USA
Carey Mulligan,27,F,UK
Gong Li,45,F,China
How do we do that ? Are there any open source libraries to do this task ?
CSV format is not very well defined. You don't have to write headers for the file. Instead it is pretty SIMPLE format. Data values are separated using commas or semicolon or space etc.
You just have to write your own simple method that writes your string to a file on local computer using FileOutputStream or Writer in java.io package.
You can use this as a learning example.
I used BufferedReader because he will take care about line separators, but you can also use #split method, and write the resulting tokens.
import java.io.*;
public class Tests {
public static void main(String[] args) {
File file = new File("out.csv");
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
String string = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(string.getBytes())));
String line;
while ((line = reader.readLine()) != null) {
out.write(line.trim());
out.newLine();
}
}
catch (IOException e) {
// log something
e.printStackTrace();
}
finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignored
}
}
}
}
}
This is pretty simple
String str = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
PrintWriter pr = new PrintWriter(new FileWriter(new File("test.csv"), true));
String arr[] = str.split("\\n");
// splited the string by new line provided with the string
pr.println("Name,Age,Gender,Country");
// header written first and rest of data appended
for(String s : arr){
pr.println(s);
}
pr.close();
don't forget to close the stream in finally block and handle the exception
i was wondering if there was a way to add to text files already created. because when i do this on an already created file:
public Formatter f = new Formatter("filename.txt");
it re-writes the current filename.txt with a blank one.
thanks, Quinn
Yes, use the constructor with an OutputStream argument instead of a File argument. That way you can open an OutputStream in append mode and do your formatting on that. Link
Try using the constructor for Formatter which takes an Appendable as an argument.
There are several classes which implement the Appendable interface. The most convenient, in your case, should be FileWriter.
This FileWrite constructor will let you open a file (whose name is specified as a String), in append mode.
Use FileOutputStream with append boolean value as true eg new FileOutputStream("C:/concat.txt", true));
Example
public class FileCOncatenation {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/concat.txt", true));
File file2 = new File("C:/Text/file2.rxt");
System.out.println("Processing " + file2.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(file2
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
// }
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}
}
I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What's wrong?
try {
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out.close();
}
catch(IOException e1) {
System.out.println("Error during reading/writing");
}
You need to do something like this:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out attribute to be the supplied PrintStream value.
There are analogous methods (setIn and setErr) for changing the standard input and error streams; refer to the java.lang.System javadocs for details.
A more general version of the above is this:
PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
If append is true, the stream will append to an existing file instead of truncating it. If autoflush is true, the output buffer will be flushed whenever a byte array is written, one of the println methods is called, or a \n is written.
I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logback or the standard Java java.util.logging subsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
Alternatively, if you are not "logging" then consider the following:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
$ java MyApp > output.txt
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an out stream passed as a method parameter or via a singleton or dependency injection rather than writing to System.out.
Changing System.out may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out and System.err, but you could be unlucky.)
There is no need to write any code, just in cmd
on the console you can write:
javac myFile.java
java ClassName > a.txt
The output data is stored in the a.txt file.
to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:
public class TeePrintStream extends PrintStream {
private final PrintStream second;
public TeePrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
/**
* Closes the main stream.
* The second stream is just flushed but <b>not</b> closed.
* #see java.io.PrintStream#close()
*/
#Override
public void close() {
// just for documentation
super.close();
}
#Override
public void flush() {
super.flush();
second.flush();
}
#Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
#Override
public void write(int b) {
super.write(b);
second.write(b);
}
#Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
and used as in:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(just an idea, not complete)
Create the following method:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
Then instead of System.out.println(str) call Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more
In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.
You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.
This is my idea of what you are trying to do and it works fine:
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
try {
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("eof"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
The easiest way to write console output to text file is
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();
To write console output to a txt file
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to generate the PDF rather then the text file, you use the dependency given below:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
To generate a PDF, use this code:
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
Document document = new Document();
try {
PdfWriter writer1 = PdfWriter
.getInstance(
document,
new FileOutputStream(
"final_pdf.pdf"));
document.open();
document.add(new Paragraph(listString));
document.close();
writer1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("C:\\testing.txt"));
} catch (IOException e) {
e.printStackTrace();
}
out.println("output");
out.close();
I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.
In netbeans, you can right click the mouse and then save as a .txt file. Then, based on the created .txt file, you can convert to the file in any format you want to get.