I use This methods to Write to a text file(use getResource()... to use in JAR file).
My files are in Classpath,
Here is my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class JarWrite {
public JarWrite(){
writethis();
}
public void writethis(){
try{
InputStreamReader isReader= new InputStreamReader(this.getClass().getResourceAsStream("AllBookRecords.txt"));
BufferedReader br = new BufferedReader(isReader);
PrintWriter writer1=new PrintWriter(new File(this.getClass().getResource("Boutput.txt").getPath()));
String Bs;
while( (Bs=br.readLine()) != null ){
writer1.println(Bs);
}
writer1.close();
br.close();
} catch(FileNotFoundException fnfe){
} catch(IOException ioe){
ioe.printStackTrace();
}
}
public static void main(String[] args){
new JarWrite();
}
}
You can't modify resources from CLASSPATH. They are read only. Period.
See also: Java OutputStream equivalent to getClass().getClassLoader().getResourceAsStream().
Try changing:
public void writethis
to
public static void writethis
Related
Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* BufferedReader and Scanner can be used to read
line by line from any File or
* console in Java.
* This Java program
demonstrate line by line reading using BufferedReader in Java
*
* #author Javin Paul
*/
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}
I have a question about Apache Commons IO with Java.
The excercice is to read a text file without using Commons IO, and then using it.
For the first one, my code is this, and this works:
import java.util.Scanner;
public class ReadBook {
private Scanner line;
public void openFile(){
try{
line= new Scanner(new File("books.txt"));
}
catch(Exception e){
System.out.println("File not found");
}
}
public void readFile() {
while (line.hasNext()) {
String book = line.next();
System.out.println(book);
}
}
public void closeFile(){
line.close();
}
}
and the main class:
public class mainClass {
public static void main(String[] args){
ReadBook book = new ReadBook();
book.openFile();
book.readFile();
book.closeFile();
}
}
The teacher gave us this class, and now we are supposed to do the same thing with the Apache Commons IO library.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class Utf8File {
public static String loadFileIntoString(String filePath) throws FileNotFoundException, IOException {
return IOUtils.toString(new FileInputStream(filePath), "UTF-8");
}
public static void saveStringIntoFile(String filePath, String content) throws IOException {
File f = new File(filePath);
FileUtils.writeStringToFile(f, content, "UTF-8");
}
}
I was wondering, do you know how to do it?
Last time I programmed with Java was one year ago hahaha so it is a little bit far away in my memory :O
This is the first homework to do (today was the first class).
I hope someone can help me :)
Thanks!
I am a beginner in Java and trying to learn the basics of FileInputStream and FileOutputStream. I was able to successfully write the data to the file but unable to read it. Here is my code. Could you please let me know, if I am missing something to read the data.
Application.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Application {
public static void main(String[] args) throws FileNotFoundException {
try(FileOutputStream fs = new FileOutputStream("testdata.txt")){
ObjectOutputStream os = new ObjectOutputStream(fs);
MathematicalOperation mo = new MathematicalOperation();
os.writeObject(mo);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ReadingFile.Java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ReadDataFromFile {
public static void main(String[] args) throws FileNotFoundException{
try(FileInputStream fi = new FileInputStream("testdata.txt")){
ObjectInputStream oi = new ObjectInputStream(fi);
MathematicalOperation mo= (MathematicalOperation) oi.readObject();
System.out.println(mo);
oi.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
If you're trying to read the content of the .txt file, just use FileInputStream class.
Also, it would be of great help if you coul
While writing to the file "testdata.txt" you are passing object of MathematicalOperation class, you can set values of the class members before writing file (e.g. mo.setXXX()) and when you are reading that object from text file you can get those values using the return object of MathematicalOperation (e.g. mo.getXXX()) and before printing the object please override toString() method in your MathematicalOperation class to display the correct values of all fields of the class.
This program takes in input the "hello my name is bob" and spits it out backwards. I really need help making it that the program reads in a text file and spits out the text file backwards. Thanks in advance!
public class Recursion
{
public static void main(String[] args) throws FileNotFoundException {
System.out.println(printBackwards("hello my name is bob"));
}
public static String printBackwards(String s){
if(s.length() <= 1)
return s;
else
return printBackwards(s.substring(1,s.length()))+s.charAt(0);
}
}
Based on the comments for the question, this will read a file called input.txt and save it to a new file called output.txt using your method for reversing a String.
All lines in input.txt are firstly added to a List.
The List is then iterated through backwards from the last element, and with each iteration the reversed String written to output.txt.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
Scanner scanner = new Scanner(new File("input.txt"));
List<String> fileContents = new ArrayList<>();
while (scanner.hasNextLine()) {
fileContents.add(scanner.nextLine());
}
ListIterator<String> it = fileContents.listIterator(fileContents.size());
while (it.hasPrevious()) {
writer.write(printBackwards(it.previous()));
writer.newLine();
}
}
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
If however you just want to display it to the standard output, you can adjust it to the following:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("input.txt"));
List<String> fileContents = new ArrayList<>();
while (scanner.hasNextLine()) {
fileContents.add(scanner.nextLine());
}
ListIterator<String> it = fileContents.listIterator(fileContents.size());
while (it.hasPrevious()) {
System.out.println(printBackwards(it.previous()));
}
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
Or as I said in my comment earlier, you can just read the whole file in one go and reverse it:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Example {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(printBackwards(new Scanner(new File("file.txt")).useDelimiter("\\Z").next()));
}
public static String printBackwards(String s) {
if (s.length() <= 1) {
return s;
} else {
return printBackwards(s.substring(1, s.length())) + s.charAt(0);
}
}
}
Use this code to get the string that you want to reverse from a text file:
try{
String myString;
BufferedReader input = new BufferedReader(new FileReader("Filepath.txt");
while((myString = input.readLine()) != null){}
}
catch(FileNotFoundException ex){
//Error Handler Here
}
catch(IOException ex){
//Error Handler Here
} finally {
try{
if(br != null) br.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}
Don't forget to import:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException
This should work as you expect. I assume that in the filename_in.txt you have only one line, otherwise you have to loop (I let you to do this as exercise):
public static void main(String[] args){
Scanner in = null;
PrintWriter writer = null;
try{
in = new Scanner(new FileReader("filename_in.txt"));
writer = new PrintWriter("filename_out.txt");
writer.println(printBackwards(in.nextLine()));
} catch (Exception e) {
e.printStackTrace();
}
finally {
in.close();
writer.close();
}
}
Here i have written a program. I want to get input by a scanner from system. Then I want to show output from file. But after giving input , a message " The file is modyfied by another program " is shown. But i cannot see anything in this file. Please give me a suggestion to solve the problem.
package eighthLecture;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Filetester {
public static void main(String[] args) {
File outFile = new File("C:/Users/nafiulislam/Desktop/naficlass.txt");
try {
FileWriter fileWriter=new FileWriter(outFile);
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String tempString = scanner.nextLine();
System.out.println(tempString);
fileWriter.write(tempString);
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}