FileInput/outputstream not working - java

i have a simple input/output stream here:
package managingfilesanddirectories;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (
FileInputStream in = new FileInputStream("selfie.jpg");
FileOutputStream out = new FileOutputStream("newPic.jpg");) {
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
All files are in the same package, but whenever i try to make a new file, the new files are not created (both with .jpg, -and .txt files). I'm using netbeans, should i place the files in another package or directory?
i get this error:
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at managingfilesanddirectories.Main.main(Main.java:18)

For working with FileInputStream or FileOutputStream you shoukd sent ti constructor File.
For example:
File myFile = new File("C:\\exampleFile.txt");
FileInputStream inputStream;
try {
inputStream = new FileInputStream(myFile);
// reading from input stream
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} finally {
inputStream.close();
}
For better you should check that file and path are exists.

Related

Read a txt File with RandomAccessFile (Java)

I try to output the content of a text file. But I don't know how to work with the RandomAccessFile. I haven't found good examples at google. I hope for some help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
File src = new File ("C:/Users/hansbaum/Documents/Ascii.txt");
cat(src);
}
public static void cat(File quelle){
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
// while(datei.length() != -1){
// datei.seek(0); //
// }
} catch (FileNotFoundException fnfe) {
System.out.println("Datei nicht gefunden!");
} catch (IOException ioe) {
System.err.println(ioe);
}
}
}
related from doc
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
String line;
while ( (line = datei.readLine()) != null ) {
System.out.println(line);
}
System.out.println();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
System.err.println(ioe);
}
What makes you think you need a RandomAccessFile? The easiest way is probably to use nio's convenience methods. With those, reading a file is as close to a one-liner as it gets in Java.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.IOException;
class Test {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("./Test.java"), StandardCharsets.UTF_8);
for (String l: lines)
System.out.println(l);
}
}
Be aware however that this is not a good idea if you happen to work with very large files as they might not fit into memory.
Try to create Stream from FileChannel to read and write in another file out.txt like this:
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r").getChannel();){
// Construct a stream that reads bytes from the given channel.
InputStream is = Channels.newInputStream(rChannel);
File outFile = new File("out.txt");
// Create a writable file channel
WritableByteChannel wChannel = new RandomAccessFile(outFile,"w").getChannel();
// Construct a stream that writes bytes to the given channel.
OutputStream os = Channels.newOutputStream(wChannel);
// close the channels
is.close();
os.close();

edit file from internal storage

How can I edit the content of a file located on the internal storage in my Android app.
I want to erase the whole content and then write to the file again, instead of appending data to the current content.
Here's my code to read and write:
package com.example.cargom;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class FileManager {
FileOutputStream outputStream;
FileInputStream inputStream;
public void writeToFile(Context context, String fileName, String data) {
try {
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
outputStream.write(data.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFromFile(Context context, String fileName) {
String data = "";
int c;
try {
inputStream = context.openFileInput(fileName);
while ((c = inputStream.read()) != -1) {
data = data + Character.toString((char) c);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
}
Your class is already doing what you rquire. It first erases the contents of the file and then writes on it. For further understanding,
When you initiate your stream with MODE_PRIVATE, the second time when you try to write the file, the contents that are already in the file gets erased and the new contents are written.
outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
When you use MODE_APPEND, the contents that are already there stays and the new contents will be appended to the file.
outputStream = context.openFileOutput(fileName, Context.MODE_APPEND);
For more reference and detailed knowledge on dealing with files in Internal storage, I recommend you to watch the below three short videos which gives you detailed description with demo.
http://www.youtube.com/watch?v=Jswr6tkv8ro&index=4&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
http://www.youtube.com/watch?v=cGxHphBjTBk&index=5&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
http://www.youtube.com/watch?v=mMcrj_To18k&index=6&list=PLonJJ3BVjZW5JdoFT0Rlt3ry5Mjp7s8cT
Hope it helps! Any more questions, please comment below.
You can just delete the file first with:
File f = new File(filename);
if(f.exists()){
f.delete();
}
And then create a new one with same path/name and write to it.
I'm assuming that your filename is the path to the file on the device.
But probably I'm not getting your real problem?

Writing to .properties file in java web application

I was trying to write a key value pair to a chat.properties file in java .My function to do so is something like this :
public void WritePropertiesFile() throws FileNotFoundException, IOException {
File file =
new File("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\chat.properties");
Properties configProperty = new Properties();
InputStream in = new FileInputStream(file);
configProperty.load(in);
configProperty.setProperty("newKey", "newValue");
in.close();
OutputStream outt = new FileOutputStream(file);
configProperty.store(outt, "my data");
outt.close();
}
But its not working and the data is not being entered in the file.Please help to resolve the problem.
Try this code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class MakeEntryInPropertyFile {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("C:\\Users\\admin\\Desktop\\SharedCrpto1\\web\\chat.properties");
prop.setProperty("newKey", "newValue");
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Copying files in java (Doesn't work)

I have tried many examples from the same question that has already been asked including:
IOUtils.copy();
(copy is a non-existent method)
Files.copy(source, target, REPLACE_EXISTING);
(REPLACE_EXISTING "Cannot find Symbol")
FileUtils.copyFile();
(FileUtils doesn't exist)
The problems with using them are in brackets.
Here is the code for the most repeated method for copying:
import static java.nio.file.Files;
public void Install()
{
CrtFol();
CrtImgFol();
CrtSaveFol();
CrtSaveFile();
open.runmm();
//I have added the import for "Files"
Files.copy(img1, d4, REPLACE_EXISTING);
//Compiler says "Cannot find symbol" when I go over REPLACE_EXISTING
//img1 is a File and d4 is a File as a directory
}
Are there any other ways to copy or a way to fix the one above?
With Java 7's standard library, you can use java.nio.file.Files.copy(Path source, Path target, CopyOption... options). No need to add additional dependencies or implement your own.
try {
Files.copy( Paths.get( sFrom ),
Paths.get( sTo ),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// Handle exception
}
Not sure if Java actually has anything to copy a file. The simplest way would be to convert the file into a byte stream and then write this stream to another file. Something like this:
InputStream inStream = null;
OutputStream outStream = null;
File inputFile =new File("inputFile.txt");
File outputFile =new File("outputFile.txt");
inStream = new FileInputStream(inputFile);
outStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int fileLength;
while ((fileLength = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, fileLength );
}
inStream.close();
outStream.close();
where inputFile is the file being copied from, and outputFile is the name of the copy.
I use this code:
import java.io.*;
public class CopyTest {
public CopyTest() {
}
public static void main(String[] args) {
try {
File stockInputFile = new File("C://test.txt");
File StockOutputFile = new File("C://output.txt");
FileInputStream fis = new FileInputStream(stockInputFile);
FileOutputStream fos = new FileOutputStream(StockOutputFile);
int count = 0;
while((count = fis.read()) > -1){
fos.write(count);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsReadnWrite: " + e);
} catch (IOException e) {
System.err.println("FileStreamsReadnWrite: " + e);
}
}
}
Use this code to upload file, I am working on SpringBoot...
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
#Component
public class FileUploadhelper {
public final String uploadDirectory = "D:\\SpringBoot Project\\BootRestBooks\\src\\main\\resources\\static\\image";
public boolean uploadFile(MultipartFile mf) {
boolean flag = false;
try {
Files.copy(mf.getInputStream(), Paths.get(uploadDirectory + "\\" + mf.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}

Something is wrong with this code

My homework assignment says "Write a program that reads a file and writes a copy of the file to another file with line numbers inserted" I have this code but something's wrong, can anyone help please? Thank you in advance
ShowFile:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class ShowFile {
public static void main(final String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch (final FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch (final ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = fin.read();
if (i != -1)
System.out.print((char) i);
} while (i != -1);
fin.close();
}
}
CopyFile:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class CopyFile {
public static void main(final String args[])
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch (final FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch (final FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch (final ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}
// Copy File
try {
do {
i = fin.read();
if (i != -1)
fout.write(i);
} while (i != -1);
} catch (final IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
This is the error message-
Exception in thread "main" java.lang.NoClassDefFoundError: C
Caused by: java.lang.ClassNotFoundException: C
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
How about this ...
BufferedReader reader = new BufferedReader(new FileReader("infile"));
BufferedWriter writer = new BufferedWriter(new FileWriter("outfile"));
String line;
int lineNumber = 0;
while((line = reader.readLine()) != null) {
writer.write(++lineNumber + " " + line);
writer.newLine();
}
writer.close();
reader.close();
I think that the problem must be in the way that you are running the program. The exception seems to be saying that it can't find a class called "C".
My guess is that you have supplied the name of the class to be executed as a pathname not as a classname. Please read the manual page for the java command carefully.
There is no problem in your code.
I think you just have passing wrong argument.
Let say you have this readme.txt in your drive,
you must run this, like this :
java ShowFile "C:\readme.txt"

Categories

Resources