I am trying to create a new file that write a string to a file. Then , I read that file and reverse the text in the file and store the text in my new file.
This is my codes
package OpenFile;
import java.io.*;
import java.util.Scanner;
public class inversetext {
public static void main(String[] args){
try {
ObjectOutputStream file = new ObjectOutputStream(new FileOutputStream("testio.txt"));
file.writeUTF("ABCDEFHIJK");
file.close();
} catch (Exception e) {
System.out.println("File cannot be created");
}
try {
Scanner input = new Scanner(new FileInputStream("testio.txt"));
ObjectOutputStream newfile = new ObjectOutputStream(new FileOutputStream("reverse.txt"));
while (input.hasNextLine()){
String read = input.nextLine();
for (int x= read.length()-1 ; x>=0 ;x--){
newfile.write(read.charAt(x));
}
}
newfile.close();
} catch (Exception e) {
System.out.println("File cannot write");
}
}
}
However , I am not receiving the intended output.
This is how my testio.txt file looks like:
’ w
ABCDEFGHIJK
But this is how my reverse.txt file looks like:
Ԁቷշ䮬䥊䝈䕆䍄䅂
So , my question is:Why am I not getting the reverse text but I got all this characters?
I have the below piece of code.
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException {
WriteLinesToFile("miss.txt","This is a special file");
}
public static void WriteLinesToFile(String outputFileName, String lineConverted) throws IOException {
File f = new File(outputFileName);
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
}
I need the same logic, without throwing exception. Could someone tell me how to do this?
You could handle your exception with a try{} catch(IOException e){}
But it's important to handle the exception, because otherwise your program will do something, but not what you want.
import java.io.*;
public class FileTest {
public static void main(String[] args)
{
writeLinesToFile("miss.txt", "This is a special file");
}
public static void writeLinesToFile(String outputFileName, String lineConverted){
File f = new File(outputFileName);
try {
if (f.createNewFile()) {
System.out.println("File is created!");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
} else {
System.out.println("File already exists.");
FileWriter writer = new FileWriter(f);
writer.write(lineConverted);
writer.close();
}
}
catch(IOException e){
//Handle your error
}
}}
But you can't cut out the exceptions at all, because handling files in java throws always exceptions (For example if the file could not be found).
In the output file "CMFTSwitchesnew.txt" only has the last line of the input file. I've tested a few different methods such as changing write.println(input.nextLine()) but I'm not sure now where the issue is.
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
You're creating a PrintWriter in each iteration without using the constructor that allows you to tell the PrintWriter to append data at the end of an already existing file. That way you only see the output of the last time the file was written. Either change that to
PrintWriter write = new PrintWriter(output, true);
or instantiate the PrintWriter outside the while-loop and close it after it.
I am trying to enter data into a text file from a java program. The program is executing and showing the output as success but when i open the text file it is still blank.
Here is my code
package com.example.ex2;
import java.io.*;
class Input{
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("abc.txt");
String s="Good MOrning";
byte b[]=s.getBytes();
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);}
}
}
I think i have gone wrong in placing the text file. I have placed it in the default directory.
Your code works fine. Check the correct file.
If you are running from IDE, it will be in the current working directory.
It is always better to your a temp or directory to store files ( certainly not in working dir)
Here is a best practice code. You can tune it further if you wish
public static void main(String args[])
{
FileOutputStream fout = null;
try
{
File f = new File("abc.txt");
if (!f.isFile())
f.createNewFile();
fout = new FileOutputStream(f);
String s = "Good MOrning";
byte b[] = s.getBytes();
fout.write(b);
System.out.println("success... printed at : " + f.getAbsolutePath());
} catch (Exception e)
{
System.out.println(e);
} finally
{
if (null != fout)
try
{
fout.close();
} catch (IOException e)
{
}
}
}
If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}