I have the following logic to open a file:
Except what I want to do is not just print the file on the screen, but to take a line and store it to a String called test.
Can someone please help me with this ?
// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);
int i;
while ((i=fileInputStream.read()) != -1)
{
System.out.write(i);
}
fileInputStream.close();
I suggest you use the BufferedReader class and use the ReadLine method to extract the line from the file.
// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test;
java.io.FileReader fileInputReader = new java.io.FileReader(filepath + filename);
java.io.BufferedReader input = new java.io.BufferedReader( fileInputReader );
while ((test=input.readLine()) != null)
{
// Do something with the line...
}
fileInputStream.close();
Use Apache Commons IO library:
String fileContents = FileUtils.readFileToString(file);
http://commons.apache.org/proper/commons-io/javadocs/api-2.4/index.html
Use StringBuilder instead of String
then
StringBuilder test=new StringBuilder();
then in your while loop
test.append("your String");
Or you can use String as you wish as follows
String test=new String();
test +=your_String;
Try this
Scanner sc=new Scanner(new FileReader("D:\\Test.txt"));
StringBuilder test=new StringBuilder();
String str;
while (sc.hasNext()){
str=sc.next();
System.out.println(str);
test.append(str);
}
To read specific line
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Read {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("D:\\Test.txt");
BufferedReader br=new BufferedReader(fr);
StringBuilder test=new StringBuilder();
String str;
int count=1;
while ((str=br.readLine())!=null){
if(count==1){
System.out.println(str);
test.append(str);
}
count++;
}
}
}
Related
From read the line needed to be deleted by the user to delete it
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Delete {
public static void main(String[] args) throws IOException {
File input = new File("data.txt");
FileReader fr = null;
Scanner ob = new Scanner(System.in);
// declare variable
String DeleteWord, str, newDeleteWord;
System.out.print("Enter word you want to delete: ");
DeleteWord = ob.nextLine();
newDeleteWord = (capitalize(DeleteWord));
try {
fr = new FileReader(input);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) != null) {
if (str.contains(newDeleteWord)) {
System.out.println(str);
}
Scanner read = new Scanner(System.in);
int selection;
System.out.println("Confirm to delete his/her data?\n 1 for yes\n 2 for no");
selection = read.nextInt();
if (selection == 1)
if (str.contains(newDeleteWord)) {
str = "";
}
}
} finally {
fr.close();
}
}
public static String capitalize(String str1) {
if (str1 == null || str1.isEmpty()) {
return str1;
}
return str1.substring(0, 1).toUpperCase() + str1.substring(1);
}
}
How can I delete lines of data in textfile using java? eg. my textfile is data.txt
This is a possible solution:
File inputFile = new File("myFile.txt"); // File which we will read
File tempFile = new File("myTempFile.txt"); // The temporary file where we will write
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = yourString; // here is your line to remove
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim(); // we trim it and remove unecessary spaces
if(trimmedLine.equals(lineToRemove)) continue; // If it is equal to our line to remove then do not write it to our file!
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete(); // we delete the file that we have so that we have no conflicts
boolean successful = tempFile.renameTo(inputFile);
OR
Reading all the lines in a list and filtering this list.
The quickest way is through Apache Commons-IO ( or you can implement it yourself)
Apache Commons:
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);
Hello can someone help me? The point of the homework is to read a file then create another file where it replaces all of the words "is" with "was", i have all this done but I am also not sopposed to replace words that have"is" in them, for example: "this, isthmus".
import java.io.*;
import java.util.*;
public class WordChange {
public static void main(String[]args) throws Exception {
FileReader fr = null;
FileWriter fw = null;
try
{
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the name of the text file: ");
String fileName=keyboard.nextLine();
File file = new File(fileName);
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String replacedtext=oldtext.replaceAll("is ","was ");
FileWriter writer = new FileWriter("output.txt");
writer.write(replacedtext);
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
just a guess here but instead of
String replacedtext=oldtext.replaceAll("is ","was ");
would this work
String replacedtext=oldtext.replaceAll(" is "," was ");
Im just guessing let me know if it works
Help guys, i've just seen this example in the web. i would like to use this to print exactly the contents of a text file in the same format containing new lines, but it just prints out the first line. thanks
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String[] args)throws Exception
{
Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
String str = scanner.nextLine();
// Convert the above string to a char array.
char[] arr = str.toCharArray();
// Display the contents of the char array.
System.out.println(arr);
}
}
public class Program {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
String str;
while ((str = scanner.nextLine()) != null)
// No need to convert to char array before printing
System.out.println(str);
}
}
The nextLine() method provides only one line, you must call it until have a null ( ~ C's EOF )
Try this.. To read the whole file as it is.....
File f = new File("B:\\input.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((s = br.readLine()) != null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
But still if you want to use Scanner then try this....
while ( scan.hasNextLine() ) {
str = scan.nextLine();
char[] arr = str.toCharArray();
}
I have the following code to open and read a file. I'm having trouble figuring out how I can have it go through and print the total number of each character in the file, print the first and last character, and print the character exactly in the middle of the file. What's the most efficient way to do this?
This is the main class:
import java.io.IOException;
public class fileData {
public static void main(String[ ] args) throws IOException {
String file_name = "/Users/JDB/NetBeansProjects/Program/src/1200.dna";
try {
ReadFile file = new ReadFile(file_name);
String[] arrayLines = file.OpenFile();
int i;
for (i=0; i<arrayLines.length; i++)
{
System.out.println(arrayLines[i]);
}
}
catch (IOException e) {
System.out.println(e.getMessage()) ;
}
}
}
and the other class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile (String file_path)
{
path = file_path;
}
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine() ) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
Some hints which might help.
A Map can be used to store information about each character in the alphabet.
The middle of the file can be found from the size of the file.
These few lines of code will do it (using Apache's FileUtils library):
import org.apache.commons.io.FileUtils;
public static void main(String[] args) throws IOException {
String str = FileUtils.readFileToString(new File("myfile.txt"));
System.out.println("First: " + str.charAt(0));
System.out.println("Last: " + str.charAt(str.length() - 1));
System.out.println("Middle: " + str.charAt(str.length() / 2));
}
Anyone who says "you can't use libraries for homework" isn't being fair - in the real world we always use libraries in preference to reinventing the wheel.
The easiest way to understand I can think of is to read the entire file in as a String. Then use the methods on the String class to get the first, last, and middle character (character at index str.length()/2).
Since you are already reading in the file a line at a time, you can use a StringBuilder to construct a string out of those lines. Using the resulting String, the charAt() and substring() methods you should be able to get out everything you want.
i'm doing tokenizing a text file in java. I want to read an input file, tokenize it and write a certain character that has been tokenized into an output file. This is what i've done so far:
package org.apache.lucene.analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
class StringProcessing {
// Create BufferedReader class instance
public static void main(String[] args) throws IOException {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyboardInput = new BufferedReader(input);
System.out.print("Please enter a java file name: ");
String filename = keyboardInput.readLine();
if (!filename.endsWith(".DAT")) {
System.out.println("This is not a DAT file.");
System.exit(0);
}
File File = new File(filename);
if (File.exists()) {
FileReader file = new FileReader(filename);
StreamTokenizer streamTokenizer = new StreamTokenizer(file);
int i = 0;
int numberOfTokensGenerated = 0;
while (i != StreamTokenizer.TT_EOF) {
i = streamTokenizer.nextToken();
numberOfTokensGenerated++;
}
// Output number of characters in the line
System.out.println("Number of tokens = " + numberOfTokensGenerated);
// Output tokens
for (int counter = 0; counter < numberOfTokensGenerated; counter++) {
char character = file.toString().charAt(counter);
if (character == ' ') { System.out.println(); } else { System.out.print(character); }
}
} else {
System.out.println("File does not exist!");
System.exit(0);
}
System.out.println("\n");
}//end main
}//end class
When i run this code, this is what i get:
Please enter a java file name: D://eclipse-java-helios-SR1-win32/LexractData.DAT
Number of tokens = 129
java.io.FileReader#19821fException in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(Unknown Source)
at org.apache.lucene.analysis.StringProcessing.main(StringProcessing.java:40)
The input file will look like this:
-K1 Account
--Op1 withdraw
---Param1 an
----Type Int
---Param2 amount
----Type Int
--Op2 deposit
---Param1 an
----Type Int
---Param2 Amount
----Type Int
--CA1 acNo
---Type Int
-K2 CheckAccount
--SC Account
--CA1 credit_limit
---Type Int
-K3 Customer
--CA1 name
---Type String
-K4 Transaction
--CA1 date
---Type Date
--CA2 time
---Type Time
-K5 CheckBook
-K6 Check
-K7 BalanceAccount
--SC Account
I just want to read the string which are starts with -K1, -K2, -K3, and so on... can anyone help me?
The problem is with this line --
char character = file.toString().charAt(counter);
file is a reference to a FileReader that does not implement toString() .. it calls Object.toString() which prints a reference around 25 characters long. Thats why your exception says OutofBoundsException at the 26th character.
To read the file correctly, you should wrap your filereader with a bufferedreader and then put each readline into a stringbuffer.
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
// Now use sb.toString() instead of file.toString()
If you are wanting to tokenize the input file then the obvious choice is to use a Scanner. The Scanner class reads a given input stream, and can output either tokens or other scanned types (scanner.nextInt(), scanner.nextLine(), etc).
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("filename.dat"));
while (in.hasNext) {
String s = in.next(); //get the next token in the file
// Now s contains a token from the file
}
}
Check out Oracle's documentation of the Scanner class for more info.
public class FileTokenize {
public static void main(String[] args) throws IOException {
final var lines = Files.readAllLines(Path.of("myfile.txt"));
FileWriter writer = new FileWriter( "output.txt");
String data = " ";
for (int i = 0; i < lines.size(); i++) {
data = lines.get(i);
StringTokenizer token = new StringTokenizer(data);
while (token.hasMoreElements()) {
writer.write(token.nextToken() + "\n");
}
}
writer.close();
}