Learning Java by coding...
Read and write text file to insert tabs to further be imported into Mnemosyne
I got a text file written by hand by myself like this:
First line of text\tansewer
Second line of text\tanswer
Third line of text\tansewer
However when I try to print it or write it to a file I don't get the tab I need.
public static void main(String[] args) {
String fileName = "jeg.txt";
String line = null;
String[] mylines = new String[20];
int i = 0;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
mylines[i++] = line;
}
bufferedReader.close();
}
All you are doing is reading the information into a variable. Once you have the information, you have to output it somewhere for it to show up.
public static void main(String[] args) {
String fileName = "jeg.txt";
String line = null;
String[] mylines = new String[20];
int i = 0;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
mylines[i++] = line;
}
bufferedReader.close();
}
for(int j=0;j<i;j++){
System.out.println(mylines[j]);
}
This will output your lines to the system line. You can use the same concept in a tab or anywhere else.
Related
This is my following .txt file
.txt file
I want to retrieve IP address based on URl.I have tried the following code but it got failed.Can i do it using Hashmap. This is my first post.I apologize for my mistakes.
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt");
BufferedReader br = new BufferedReader(fr);
Scanner in = new Scanner(System.in);
System.out.println("enter:");
String output = in.next();
String line;
while((line = br.readLine()) != null){
if (line.contains(output))
{
output = line.split(":")[1].trim();
System.out.println(output);
break;
}
else
System.out.println("UrL not found");
break;
}
in.close();
}}
public static void main(String args[]) throws IOException {
FileReader fr = new FileReader("C:/Users/charan/Desktop/Resources/HashCheck.txt");
BufferedReader br = new BufferedReader(fr);
Scanner in = new Scanner(System.in);
System.out.println("enter:");
String output = in.next();
String line;
String myIp = null; //assign a new variable to put IP into
while ((line = br.readLine()) != null) {
if (line.contains(output)) {
myIp = line.split(":")[1].trim(); //assign IP to the new variable
System.out.println(myIp);
break; //break only if you get the IP. else let it iterate over all the elements.
}
}
in.close();
if (myIp == null) { //if the new variable is still null, IP is not found
System.out.println("UrL not found");
}
}
My text file includes:
Mary,123,s100,59.2
Melinda,345,A100,10.1
Hong,234,S200,118.2
Ahmed,678,S100,58.5
Rohan,432,S200,115.5
Peter,654,S100,59.5
My code:
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("competitors.txt")) ;
String line;
ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
lines.add(line);
}
String[] lineobject= {lines.get(0)};
System.out.println(lineobject[0]);
}
}
I don't know why it can not get the single value of first row, can anyone help?Thanks.
lines.get(0) is "Mary,123,s100,59.2", not {"Mary","123","s100","59.2"}
So you should do;
String[] lineobjects = lines.get(0).split(",");
System.out.println(lineobjects);
System.out.println(lineobjects[0]); // prints "Mary"
Your code works fine for me. However, you should make sure to place the file competitors.txt in the right directory.
This is simpler and should also do the job:
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("competitors.txt"));
System.out.println(lines.get(0));
}
You may replace the line with some another signs instead of using, (I use %in my case),and split using.split("%"),Then store in a vector file..
Vector data;
Vector columns;
String line;
data = new Vector();
columns = new Vector();
try {
FileInputStream fis = new FileInputStream(PRJT_PATH+"\\YOUR\\PROJECT\\"+PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
columns.addElement(st1.nextToken());
int i=0;
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens()){
data.addElement(st2.nextToken());}
String clr[]=line.split("%");
Vector v=new Vector();
v.add(clr[0]);
v.add(clr[1]);
i++;
}
br.close();
fis.close();
} catch (Exception e) {
e.getMessage();
}
I want the results from 'name' and 'code' to be inserted into log.txt file, but if I run this program only the name results gets inserted into .txt file, I cannot see code results appending under name. If I do System.outprintln(name) & System.outprintln(code) I get results printed in console but its not being inserted in a file.Can someone tell me what am I doing wrong?
Scanner sc = new Scanner(file, "UTF-8");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("text1")) {
String[] splits = line.split("=");
String name = splits[2];
for (int i = 0; i < name.length(); i++) {
out.println(name);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
String code = splits[2];
for (int i = 0; i < code.length(); i++) {
out.println(code);
}
}
out.close()
}
File looks like:
Name=111111111
Code=333,5555
Category-Warranty
Name=2222222
Code=111,22
Category-Warranty
Have a look at this code. Does that work for you?
final String NAME = "name";
final String CODE = "code";
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
String[] splits = line.split("=");
String key = splits[0];
String value = splits[1];
if (key.equals(NAME) || key.equals(CODE)) {
out.println(value);
}
}
out.close();
You have a couple of problems in your code:
you never actually assign the variables name and code.
you close() your PrintWriter inside the while-loop, that means you will have a problem if you read more than one line.
I don't see why this wouldn't work, without seeing more of what you are doing:
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter out = new PrintWriter(new FileWriter("log.txt", true));
while ((line = br.readLine()) != null) {
if (line.contains("=")) {
if (line.contains("text1")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
if (line.contains("text2")) {
String[] splits = line.split("=");
if (splits.length >= 2) {
out.println(splits[1]);
}
}
}
}
out.flush();
out.close();
Make sure the second if condition is satisfied i.e. the line String contains "text2".
I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.
I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.