How does one use a specified file path rather than a file from the resource folder as an input or output stream? This is the class I have and I would like to read from a specific file path instead of placing the txt file in the resources folder in IntelliJ. Same for an output stream. Any help rendered would be appreciated thanks.
Input Stream
import java.io.*;
import java.util.*;
public class Example02 {
public static void main(String[] args) throws FileNotFoundException {
// STEP 1: obtain an input stream to the data
// obtain a reference to resource compiled into the project
InputStream is = Example02.class.getResourceAsStream("/file.txt");
// convert to useful form
Scanner in = new Scanner(is);
// STEP 2: do something with the data stream
// read contents
while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
// STEP 3: be polite, close the stream when done!
// close file
in.close();
}
}
Output stream
import java.io.*;
public class Example03
{
public static void main(String []args) throws FileNotFoundException
{
// create/attach to file to write too
// using the relative filename will cause it to create the file in
// the PROJECT root
File outFile = new File("info.txt");
// convert to a more useful writer
PrintWriter out = new PrintWriter(outFile);
//write data to file
for(int i=1; i<=10; i++)
out.println("" + i + " x 5 = " + i*5);
//close file - required!
out.close();
}
}
Preferred way for getting InputStream is java.nio.file.Files.newInputStream(Path)
try(final InputStream is = Files.newInputStream(Paths.get("/path/to/file")) {
//Do something with is
}
Same for OutputStream Files.newOutputStream()
try(final OutputStream os = Files.newOutputStream(Paths.get("/path/to/file")) {
//Do something with os
}
Generally, here is official tutorial from Oracle to working with IO.
First you have to define the path you want to read the file from, absolute path like so:
String absolutePath = "C:/your-dir/yourfile.txt"
InputStream is = new FileInputStream(absolutePath);
It's similar for writing the file as well:
String absolutePath = "C:/your-dir/yourfile.txt"
PrintWriter out = new PrintWriter(new FileOutputStream(absolutePath));
You can use a file object as:
File input = new File("C:\\[Path to file]\\file.txt");
Related
I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.
Is it possible to create a Java program which recognizes the text in a .txt file and write it in a .csv file? If yes,how would you start with such a problem?
My .txt file is Text1 |Text 2 so I could somehow get the char "|" and split it into two cells.
This is very simple in Java 8:
public static void main(String[] args) throws Exception {
final Path path = Paths.get("path", "to", "folder");
final Path txt = path.resolve("myFile.txt");
final Path csv = path.resolve("myFile.csv");
try (
final Stream<String> lines = Files.lines(txt);
final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
lines.map((line) -> line.split("\\|")).
map((line) -> Stream.of(line).collect(Collectors.joining(","))).
forEach(pw::println);
}
}
First you get your files at Path objects.
Then you open a PrintWriter to your destination Path.
Now you do some Java 8 stream processing with lambdas:
Files.lines(txt) streams the lines from the file
map((line) -> line.split("\\|")) splits each line to a String[] on |
map((line) -> Stream.of(line).collect(Collectors.joining(","))) joins the individual String[] again using ,
forEach(pw::println) writes the new lines to the destination file.
Using import static:
try (
final Stream<String> lines = Files.lines(txt);
final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
lines.map((line) -> line.split("\\|")).
map((line) -> Stream.of(line).collect(joining(","))).
forEach(pw::println);
}
As Java 8 was released only yesterday here is a Java 7 solution:
public static void main(String[] args) throws Exception {
final Path path = Paths.get("path", "to", "folder");
final Path txt = path.resolve("myFile.txt");
final Path csv = path.resolve("myFile.csv");
final Charset utf8 = Charset.forName("UTF-8");
try (
final Scanner scanner = new Scanner(Files.newBufferedReader(txt, utf8));
final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
while (scanner.hasNextLine()) {
pw.println(scanner.nextLine().replace('|', ','));
}
}
}
Again, with import static:
try (
final Scanner scanner = new Scanner(newBufferedReader(txt, utf8));
final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
while (scanner.hasNextLine()) {
pw.println(scanner.nextLine().replace('|', ','));
}
}
Yes it is very much possible.
Replace | by , and
write it to a csv
public class NewClass {
public static void main(String[] args) throws IOException {
String data = "one|two|three|four"+"\n"+
"one|two|three|four";
//Use a BufferedReader to read from actual Text file
String csv = data.replace("|", ",");
System.out.println(csv);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("MyCSV.csv")));
out.println(csv);
out.close();
}
}
Output
run:
one,two,three,four
one,two,three,four
BUILD SUCCESSFUL (total time: 0 seconds)
You first need to How do I create a Java string from the contents of a file?.
Then you can take advantage of How to split a string in Java and use | as the delimiter.
As the last step you can use the Joiner to create the final String and store it using How do I save a String to a text file using Java?.
Yes it is possible. To accomplish your task read about Input- and OutputStreams.
Start with a simple example. Read a line of text from a file and print it out on the console.
Then do it the other way - write a line of text into a file.
The experience you get through these examples will help to accomplish your task.
try this may help
public class Test {
public static void main(String[] args) throws URISyntaxException,
IOException {
FileWriter writer = null;
File file = new File("d:/sample.txt");
Scanner scan = new Scanner(file);
File file2 = new File("d:/CSV.csv");
file.createNewFile();
writer = new FileWriter(file2);
while (scan.hasNext()) {
String csv = scan.nextLine().replace("|", ",");
System.out.println(csv);
writer.append(csv);
writer.append("\n");
writer.flush();
}
}
}
sample.txt:-
He|looked|for|a|book.
He|picked|up|the|book.
Commons CSV is useful for handling CSV output in your Java code too - in particular it takes care of gotchas such as quoting, etc:
http://commons.apache.org/proper/commons-csv/
Also commons IO is really useful for simplifying reading/writing files too:
https://commons.apache.org/proper/commons-io/description.html
HTH
I am using java File Streams. I have two files. First file may or may not be empty. The second file contains strings and floats. If the first file is empty then I want to copy second file in it. else I want to merge the files.
Have tried RandomAccessFile but it's not working.
If you want to copy a file then use
public static Path copy(Path source,
Path target,
CopyOption... options)
throws IOException
File.copy()
If you want to merge them then open the file in write mode in which you want to append the data with appending mode.
BufferedWriter bw = new BufferedWritr(new FileWriter("file.txr",true));
and then write the data in bw which you have read from the source file.
My solution would look like this:
public void CopyFile(File one, File two) throws IOException {
// Declare the reader and the writer
BufferedReader in = new BufferedReader(new FileReader(one));
BufferedWriter out;
String contentOfFileOne = "";
// Read the content of the first file
while(in.ready()){
contentOfFileOne += in.readLine();
}
// Trim all whitespaces
contentOfFileOne.trim();
// If the first file is empty
if(contentOfFileOne.isEmpty()){
// Create a new Writer to the first file and a reader
// from the second file
in.close();
out = new BufferedWriter(new FileWriter(one));
in = new BufferedReader(new FileReader(two));
while(in.ready()){
String currentLine = in.readLine();
out.write(currentLine);
}
// Close them accordingly
in.close();
out.close();
} else {
// If the first file contains something
in.close();
out = new BufferedWriter(new FileWriter(one,true));
in = new BufferedReader(new FileReader(two));
// Copy the content of file two at the end of file one
while(in.ready()){
String currentLine = in.readLine();
out.write(currentLine);
}
in.close();
out.close();
}
}
The comments should explain the functionality.
I think this is supposed to be the most efficient option
FileChannel f1 = FileChannel.open(Paths.get("1"), StandardOpenOption.APPEND);
FileChannel f2 = FileChannel.open(Paths.get("2"));
f1.transferFrom(f2, f1.size(), Long.MAX_VALUE);
I want to take the content of one text file chosen by the user and add it to another text file without replacing the current content. So for example:
Update: How do I add it to the second file in a numbered way?
TextFile1:
AAA BBB CCC
AAA BBB CCC
TextFile2: (After copying)
EEE FFF GGG
AAA BBB CCC
AAA BBB CCC
Update: I had to remove my code as it may be taken for plagiarism, This was answered so I know what to do, thanks for everyone helping me out.
Try this
You have to use
new FileWriter(fileName,append);
This opens the file in append mode:
According to the javadoc it says
Parameters:
fileName String The system-dependent filename.
append boolean if true, then data will be written to the end of the file rather than the beginning.
public static void main(String[] args) {
FileReader Read = null;
FileWriter Import = null;
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Read = new FileReader(filename);
Import = new FileWriter("songstuff.txt",true);
int Rip = Read.read();
while(Rip!=-1) {
Import.write(Rip);
Rip = Read.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(Read);
close(Import);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
// JavaProgram();
}
}
Use new FileWriter("songstuff.txt", true); to append to the file instead of overwriting it.
Refer : FileWriter
You can use Apache commons IO.
Apache Commons IO
Example:
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.io.FileUtils;
public class HelpTest {
public static void main(String args[]) throws IOException, URISyntaxException {
String inputFilename = "test.txt"; // get from the user
//Im loading file from project
//You might load from somewhere else...
URI uri = HelpTest.class.getResource("/" + inputFilename).toURI();
String fileString = FileUtils.readFileToString(new File(uri));
// output file
File outputFile = new File("C:\\test.txt");
FileUtils.write(outputFile, fileString, true);
}
}
Append the file
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
new FileWriter(fileName,true);
A file channel that is open for writing may be in append mode .. http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html
also have a look at ..
http://docs.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)
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.